Skip to content

Commit

Permalink
Merge pull request #29 from rcsim/fix/remove_dup_category
Browse files Browse the repository at this point in the history
  • Loading branch information
victorptoledo authored Jan 29, 2024
2 parents d65cddb + 358d5a7 commit e97832c
Show file tree
Hide file tree
Showing 15 changed files with 60 additions and 87 deletions.
6 changes: 3 additions & 3 deletions schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ var video3 = db.videos.insertOne({
"publishDate": "2010-07-16",
"category": category1,
"views": 150,
"favoritedBy": [user1, user2]
"favoritedBy": null
}).insertedId;

var video4 = db.videos.insertOne({
Expand All @@ -58,5 +58,5 @@ var video4 = db.videos.insertOne({


// Update the users documents with the _id fields of the videos documents
db.users.updateOne({ "_id": user1 }, { "$set": { "favorites": [video1] } });
db.users.updateOne({ "_id": user2 }, { "$set": { "favorites": [video2] } });
db.users.updateOne({ "_id": user1 }, { "$set": { "favorites": [video1, video4] } });
db.users.updateOne({ "_id": user2 }, { "$set": { "favorites": [video2, video4] } });
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public Flux<VideoDTO> getVideoByPublishDate(@PathVariable("publishDate") LocalDa
@ApiResponse(responseCode = "422", description = "Parâmetro não pode ser nulo")})
@GetMapping(value = "category/{category}")
public Flux<VideoDTO> getVideoByCategory(@PathVariable("category") String category) {
return videoService.getVideoByCategory(category);
return videoService.getVideosByCategory(category);
}

@Operation(summary = "Salva um vídeo", description = "Salva um vídeo na base de dados do sistema.")
Expand Down
6 changes: 0 additions & 6 deletions src/main/java/com/postech30/movies/dto/VideoDTO.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,4 @@ public class VideoDTO {
@JsonProperty
private String category;

@JsonProperty
private String categoryName;

@JsonProperty
private String categoryDescription;

}
4 changes: 1 addition & 3 deletions src/main/java/com/postech30/movies/entity/Video.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,6 @@ public class Video {
private String url;
private LocalDate publishDate;
private Integer views;
private String category;
private List<ObjectId> favoritedBy;
private String categoryName;
private String categoryDescription;
private ObjectId category;
}
7 changes: 2 additions & 5 deletions src/main/java/com/postech30/movies/mapper/VideoMapper.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,7 @@ public static VideoDTO mapToVideoDTO(Video video) {
video.getFavoritedBy().stream()
.map(ObjectId::toHexString)
.collect(Collectors.toList()) : null)
.categoryName(video.getCategoryName())
.categoryDescription(video.getCategoryDescription())
.category(video.getCategory() != null ? video.getCategory().toHexString() : null)
.build();
}

Expand All @@ -34,13 +33,11 @@ public static Video mapToVideo(VideoDTO videoDTO) {
videoDTO.getUrl(),
videoDTO.getPublishDate(),
videoDTO.getViews(),
videoDTO.getCategory(),
videoDTO.getFavoritedBy() != null ?
videoDTO.getFavoritedBy().stream()
.map(ObjectId::new)
.collect(Collectors.toList()) : null,
videoDTO.getCategoryName(),
videoDTO.getCategoryDescription()
videoDTO.getCategory() != null ? new ObjectId(videoDTO.getCategory()) : null
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public interface VideoRepository extends ReactiveMongoRepository<Video, String>
Flux<Video> findByPublishDate(LocalDate publishDate);


Flux<Video> findByCategoryName(String categoryName);
Flux<Video> findByCategory(ObjectId category);


@Aggregation("{ $count: 'totalVideos' }")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,6 @@ public Flux<Video> getRecommendedVideos(String userId) {
return userRepository.findById(userId)
.flatMapMany(user -> Flux.fromIterable(user.getFavorites())
.flatMap(videoId -> videoRepository.findById(videoId.toString()))
.flatMap(video -> videoRepository.findVideosByCategory(new ObjectId(video.getCategory()))));
.flatMap(video -> videoRepository.findVideosByCategory(video.getCategory())));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,21 +44,11 @@ public class VideoServiceImpl implements VideoService {
public Flux<VideoDTO> getAllVideos(Pageable pageable) {
List<AggregationOperation> operations = new ArrayList<>();

operations.add(Aggregation.lookup("categories", "category", "_id", "categoryInfo"));
operations.add(Aggregation.unwind("categoryInfo"));
operations.add(Aggregation.project()
.andInclude("_id", "title", "description", "url", "publishDate", "views", "favoritedBy")
.and("categoryInfo.name").as("categoryName")
.and("categoryInfo.description").as("categoryDescription"));

// Add sorting operations from pageable
for (Sort.Order order : pageable.getSort()) {
operations.add(new SortOperation(Sort.by(order.getDirection(), order.getProperty())));
}

// Add default sorting operation by publishDate in descending order
operations.add(Aggregation.sort(Sort.Direction.DESC, "publishDate"));

// Add paging operations
operations.add(Aggregation.skip((long) pageable.getPageNumber() * pageable.getPageSize()));
operations.add(Aggregation.limit(pageable.getPageSize()));
Expand All @@ -69,7 +59,7 @@ public Flux<VideoDTO> getAllVideos(Pageable pageable) {
Video.class
);

return videoFlux.map(VideoMapper::mapToVideoDTO).switchIfEmpty(Flux.empty());
return videoFlux.map(VideoMapper::mapToVideoDTO);
}

@Override
Expand All @@ -91,20 +81,8 @@ public Flux<VideoDTO> getVideoByPublishDate(LocalDate publishDate) {
}

@Override
public Flux<VideoDTO> getVideoByCategory(String categoryName) {
MatchOperation matchStage = Aggregation.match(new Criteria("categoryInfo.name").is(categoryName));

Aggregation aggregation = Aggregation.newAggregation(
Aggregation.lookup("categories", "category", "_id", "categoryInfo"),
Aggregation.unwind("categoryInfo"),
matchStage,
Aggregation.project()
.andInclude("_id", "title", "description", "url", "publishDate", "views", "favoritedBy")
.and("categoryInfo.name").as("categoryName")
.and("categoryInfo.description").as("categoryDescription")
);

Flux<Video> videoMono = reactiveMongoTemplate.aggregate(aggregation, "videos", Video.class);
public Flux<VideoDTO> getVideosByCategory(String category) {
Flux<Video> videoMono = videoRepository.findByCategory(new ObjectId(category));
return videoMono.map(VideoMapper::mapToVideoDTO);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public interface VideoService {

Flux<VideoDTO> getVideoByPublishDate(LocalDate publishDate);

Flux<VideoDTO> getVideoByCategory(String categoryName);
Flux<VideoDTO> getVideosByCategory(String categoryName);

Mono<VideoDTO> saveVideo(VideoDTO videoDTO);

Expand Down
16 changes: 8 additions & 8 deletions src/main/resources/postman/Category.postman_collection.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,15 @@
"method": "GET",
"header": [],
"url": {
"raw": "localhost:8080/api/categories/6589d94b866c274a83a3eefa",
"raw": "localhost:8080/api/categories/65b56b440c75f588c2abf86a",
"host": [
"localhost"
],
"port": "8080",
"path": [
"api",
"categories",
"6589d94b866c274a83a3eefa"
"65b56b440c75f588c2abf86a"
]
}
},
Expand All @@ -60,15 +60,15 @@
}
},
"url": {
"raw": "localhost:8080/api/categories/6589fcc94ac9e968138a83fa",
"raw": "localhost:8080/api/categories/65b56b440c75f588c2abf86a",
"host": [
"localhost"
],
"port": "8080",
"path": [
"api",
"categories",
"6589fcc94ac9e968138a83fa"
"65b56b440c75f588c2abf86a"
]
}
},
Expand All @@ -81,7 +81,7 @@
"header": [],
"body": {
"mode": "raw",
"raw": "{\r\n \"name\": \"Action 2\",\r\n \"description\": \"Action movies involve instances of physical action such as fights, stunts, car chases, etc.\"\r\n}",
"raw": "{\r\n \"name\": \"Romance\",\r\n \"description\": \"Romance movies are centered around the theme of love and relationships.\"\r\n}",
"options": {
"raw": {
"language": "json"
Expand All @@ -103,20 +103,20 @@
"response": []
},
{
"name": "New Request",
"name": "Delete A Category",
"request": {
"method": "DELETE",
"header": [],
"url": {
"raw": "localhost:8080/api/categories/6589fcc94ac9e968138a83fa",
"raw": "localhost:8080/api/categories/65b6d7ca05c12f06ccc41b69",
"host": [
"localhost"
],
"port": "8080",
"path": [
"api",
"categories",
"6589fcc94ac9e968138a83fa"
"65b6d7ca05c12f06ccc41b69"
]
}
},
Expand Down
30 changes: 30 additions & 0 deletions src/main/resources/postman/Stream.postman_collection.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"info": {
"_postman_id": "b85db07e-0c7d-4287-a9e6-7b29a0226d85",
"name": "Stream",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
"_exporter_id": "17475893"
},
"item": [
{
"name": "Stream a Video",
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "http://localhost:8080/stream/1",
"protocol": "http",
"host": [
"localhost"
],
"port": "8080",
"path": [
"stream",
"1"
]
}
},
"response": []
}
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -153,10 +153,8 @@ public void testGetRecommendations() {
// Configurar dados de exemplo
String userId = "exampleUserId";
Video video1 = new Video("12334", "Example Title", "Example Description", "https://example.com", LocalDate.now(),
1000,
Arrays.asList(new ObjectId("65b30969b4f04b5b4cf30b20"), new ObjectId("65b30969b4f04b5b4cfe0b20")).toString(),
Collections.singletonList(new ObjectId("65b30969b4f04b5b4cfe0ba0")), "Example Category Name",
"Example Category Description");
1000, Arrays.asList(new ObjectId("65b30969b4f04b5b4cf30b20"), new ObjectId("65b30969b4f04b5b4cf30b20")),
new ObjectId("65b30969b4f04b5b4cf30b20"));

when(userService.getRecommendedVideos(userId)).thenReturn(Flux.just(video1));

Expand Down
12 changes: 3 additions & 9 deletions src/test/java/com/postech30/movies/entity/VideoTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,7 @@ class VideoTest {
@Test
void testGettersAndSetters() {
Video actualVideo = new Video();
actualVideo.setCategory("Category");
actualVideo.setCategoryDescription("Category Description");
actualVideo.setCategoryName("Category Name");
actualVideo.setCategory(new ObjectId("65b56b440c75f588c2abf86b"));
actualVideo.setDescription("The characteristics of someone or something");
ArrayList<ObjectId> favoritedBy = new ArrayList<>();
actualVideo.setFavoritedBy(favoritedBy);
Expand All @@ -26,19 +24,15 @@ void testGettersAndSetters() {
actualVideo.setTitle("Dr");
actualVideo.setUrl("https://example.org/example");
actualVideo.setViews(1);
String actualCategory = actualVideo.getCategory();
String actualCategoryDescription = actualVideo.getCategoryDescription();
String actualCategoryName = actualVideo.getCategoryName();
ObjectId actualCategory = actualVideo.getCategory();
String actualDescription = actualVideo.getDescription();
List<ObjectId> actualFavoritedBy = actualVideo.getFavoritedBy();
String actualId = actualVideo.getId();
LocalDate actualPublishDate = actualVideo.getPublishDate();
String actualTitle = actualVideo.getTitle();
String actualUrl = actualVideo.getUrl();
assertEquals("42", actualId);
assertEquals("Category Description", actualCategoryDescription);
assertEquals("Category Name", actualCategoryName);
assertEquals("Category", actualCategory);
assertEquals(new ObjectId("65b56b440c75f588c2abf86b"), actualCategory);
assertEquals("Dr", actualTitle);
assertEquals("The characteristics of someone or something", actualDescription);
assertEquals("https://example.org/example", actualUrl);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,8 @@ public void testGetRecommendedVideos() {
User user = new User("1", "teste", "[email protected]", Arrays.asList(new ObjectId("65b30969b4f04b5b4cfe0b20")));
Video video1 = new Video("12334", "Example Title", "Example Description", "https://example.com", LocalDate.now(),
1000,
Arrays.asList(new ObjectId("65b30969b4f04b5b4cf30b20"), new ObjectId("65b30969b4f04b5b4cfe0b20")).toString(),
Collections.singletonList(new ObjectId("65b30969b4f04b5b4cfe0ba0")), "Example Category Name",
"Example Category Description");
Arrays.asList(new ObjectId("65b30969b4f04b5b4cf30b20"), new ObjectId("65b30969b4f04b5b4cf30b20")),
new ObjectId("65b30969b4f04b5b4cf30b20"));
when(userRepository.findById(userId)).thenReturn(Mono.just(user));
when(videoRepository.findById("videoId1")).thenReturn(Mono.just(video1));
when(videoRepository.findVideosByCategory(new ObjectId("65b30969b4f04b5b4cfe0ba0"))).thenReturn(Flux.just(video1));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,41 +1,29 @@
package com.postech30.movies.service.Impl;

import com.amazonaws.services.s3.AmazonS3;
import com.postech30.movies.dto.FavoriteVideoDTO;
import com.postech30.movies.dto.VideoDTO;
import com.postech30.movies.entity.Category;
import com.postech30.movies.entity.User;
import com.postech30.movies.entity.Video;
import com.postech30.movies.repository.UserRepository;
import com.postech30.movies.repository.VideoRepository;
import com.postech30.movies.service.AwsService;
import org.junit.jupiter.api.Disabled;
import org.bson.types.ObjectId;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.core.io.ResourceLoader;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.ReactiveMongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.http.server.reactive.ChannelSendOperator;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import reactor.core.publisher.DirectProcessor;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.function.Function;

import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
Expand Down Expand Up @@ -141,9 +129,7 @@ void testSaveVideo2() {
when(videoRepository.save(Mockito.<Video>any())).thenReturn(justResult);
VideoServiceImpl videoServiceImpl = new VideoServiceImpl(videoRepository, mock(UserRepository.class), null);
VideoDTO.VideoDTOBuilder descriptionResult = VideoDTO.builder()
.category("Category")
.categoryDescription("Category Description")
.categoryName("Category Name")
.category("65b56b440c75f588c2abf86b")
.description("The characteristics of someone or something");
VideoDTO.VideoDTOBuilder idResult = descriptionResult.favoritedBy(new ArrayList<>()).id("42");
VideoDTO videoDTO = idResult.publishDate(LocalDate.of(1970, 1, 1))
Expand Down Expand Up @@ -237,5 +223,4 @@ void testUnfavoriteVideo2() {
verify(userRepository).findById(Mockito.<String>any());
verify(videoRepository).findById(Mockito.<String>any());
}

}

0 comments on commit e97832c

Please sign in to comment.