Skip to content

Commit b8f456e

Browse files
committed
feat: created DeletePostController controller
1 parent 09dc066 commit b8f456e

File tree

5 files changed

+235
-4
lines changed

5 files changed

+235
-4
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
package com.joaov1ct0r.restful_api_users_java.modules.posts.controllers;
2+
3+
import com.joaov1ct0r.restful_api_users_java.modules.domain.controllers.BaseController;
4+
import com.joaov1ct0r.restful_api_users_java.modules.domain.dtos.ResponseDTO;
5+
import com.joaov1ct0r.restful_api_users_java.modules.domain.repositories.EventLogsRepository;
6+
import com.joaov1ct0r.restful_api_users_java.modules.posts.dtos.DeletePostDTO;
7+
import com.joaov1ct0r.restful_api_users_java.modules.posts.dtos.PostDTO;
8+
import com.joaov1ct0r.restful_api_users_java.modules.posts.services.DeletePostService;
9+
import io.swagger.v3.oas.annotations.Operation;
10+
import io.swagger.v3.oas.annotations.responses.ApiResponse;
11+
import io.swagger.v3.oas.annotations.responses.ApiResponses;
12+
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
13+
import io.swagger.v3.oas.annotations.tags.Tag;
14+
import jakarta.servlet.http.HttpServletRequest;
15+
import jakarta.validation.Valid;
16+
import org.springframework.beans.factory.annotation.Autowired;
17+
import org.springframework.http.ResponseEntity;
18+
import org.springframework.web.bind.annotation.DeleteMapping;
19+
import org.springframework.web.bind.annotation.RequestBody;
20+
import org.springframework.web.bind.annotation.RequestMapping;
21+
import org.springframework.web.bind.annotation.RestController;
22+
import java.util.UUID;
23+
24+
@RestController
25+
@RequestMapping("/post/")
26+
@Tag(name = "Post")
27+
public class DeletePostController extends BaseController {
28+
@Autowired
29+
private DeletePostService deletePostService;
30+
31+
@Autowired
32+
private EventLogsRepository eventLogsRepository;
33+
34+
@DeleteMapping("/")
35+
@Operation(summary = "Deletar um post", description = "É possivel deletar um post já cadastrado")
36+
@ApiResponses({
37+
@ApiResponse(responseCode = "204", description = "Post deletado com sucesso!"),
38+
@ApiResponse(responseCode = "403", description = "Não permitido!"),
39+
@ApiResponse(responseCode = "500", description = "Erro interno!")
40+
})
41+
@SecurityRequirement(name = "jwt_auth")
42+
public ResponseEntity<Object> handle(
43+
HttpServletRequest req,
44+
@Valid @RequestBody DeletePostDTO dto
45+
) throws Exception {
46+
Object userIdAtt = req.getAttribute("userId");
47+
UUID userId = UUID.fromString(userIdAtt.toString());
48+
49+
PostDTO deletedPost = this.deletePostService.execute(UUID.fromString(dto.getPostId()), userId);
50+
51+
ResponseDTO response = this.responseMapper.toDTO(
52+
204,
53+
"Post deleted with success!",
54+
deletedPost
55+
);
56+
57+
this.generateEventLog(
58+
userId,
59+
204,
60+
"Usuário com id: " + userId + " deletou o post com id: " + dto.getPostId()
61+
);
62+
63+
return ResponseEntity.status(204).body(response);
64+
}
65+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package com.joaov1ct0r.restful_api_users_java.modules.posts.dtos;
2+
3+
public class DeletePostDTO {
4+
private String postId;
5+
6+
public DeletePostDTO() {}
7+
8+
public DeletePostDTO(String postId) {
9+
this.postId = postId;
10+
}
11+
12+
public String getPostId() {
13+
return this.postId;
14+
}
15+
16+
public void setPostId(String postId) {
17+
this.postId = postId;
18+
}
19+
}

src/main/java/com/joaov1ct0r/restful_api_users_java/modules/posts/services/DeletePostService.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,16 +50,16 @@ public PostDTO execute(UUID postId, UUID userId) {
5050

5151
}
5252

53-
boolean userIsNotOwnerOfPost = post.get().getUserWhoCreatedId() != user.get().getId();
53+
boolean userIsOwnerOfPost = post.get().getUserWhoCreatedId().equals(user.get().getId());
5454

55-
if (userIsNotOwnerOfPost) {
55+
if (!userIsOwnerOfPost) {
5656
this.generateErrorLog(
5757
userId,
5858
403,
5959
"Usuário com id: " + userId + " tentou excluir post com id: " + postId + ", porem não possui permissão!"
6060
);
6161

62-
throw this.forbiddenException("Não permitido!");
62+
throw this.forbiddenException("Não permitido!!!");
6363
}
6464

6565
this.postRepository.deleteById(postId);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
package com.joaov1ct0r.restful_api_users_java.modules.posts.controllers;
2+
3+
import com.github.javafaker.Faker;
4+
import com.joaov1ct0r.restful_api_users_java.modules.auth.dtos.SignInDTO;
5+
import com.joaov1ct0r.restful_api_users_java.modules.domain.dtos.ResponseDTO;
6+
import com.joaov1ct0r.restful_api_users_java.modules.posts.dtos.CreatePostDTO;
7+
import com.joaov1ct0r.restful_api_users_java.modules.posts.dtos.DeletePostDTO;
8+
import com.joaov1ct0r.restful_api_users_java.modules.posts.dtos.PostDTO;
9+
import com.joaov1ct0r.restful_api_users_java.modules.posts.repositories.PostRepository;
10+
import com.joaov1ct0r.restful_api_users_java.modules.users.dtos.UserDTO;
11+
import com.joaov1ct0r.restful_api_users_java.modules.users.entities.UserEntity;
12+
import com.joaov1ct0r.restful_api_users_java.modules.utils.TestUtils;
13+
import jakarta.servlet.http.Cookie;
14+
import org.junit.Before;
15+
import org.junit.Test;
16+
import org.junit.runner.RunWith;
17+
import org.springframework.beans.factory.annotation.Autowired;
18+
import org.springframework.boot.test.context.SpringBootTest;
19+
import org.springframework.http.MediaType;
20+
import org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers;
21+
import org.springframework.test.context.ActiveProfiles;
22+
import org.springframework.test.context.junit4.SpringRunner;
23+
import org.springframework.test.web.servlet.MockMvc;
24+
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
25+
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
26+
import org.springframework.web.context.WebApplicationContext;
27+
import java.time.LocalDateTime;
28+
import java.util.UUID;
29+
import static org.assertj.core.api.Assertions.assertThat;
30+
31+
@RunWith(SpringRunner.class)
32+
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
33+
@ActiveProfiles("test")
34+
public class DeletePostControllerTest {
35+
private MockMvc mvc;
36+
37+
private Faker faker;
38+
39+
@Autowired
40+
private WebApplicationContext context;
41+
42+
@Autowired
43+
private PostRepository postRepository;
44+
45+
@Before
46+
public void setup() {
47+
this.mvc = MockMvcBuilders.webAppContextSetup(this.context)
48+
.apply(SecurityMockMvcConfigurers.springSecurity())
49+
.build();
50+
51+
this.faker = new Faker();
52+
}
53+
54+
@Test
55+
public void shouldBeAbleToDeleteAPost() throws Exception {
56+
UUID userId = UUID.randomUUID();
57+
var createUserDTO = new UserEntity(
58+
userId,
59+
faker.name().username(),
60+
faker.internet().emailAddress(),
61+
faker.name().firstName(),
62+
faker.internet().password(),
63+
"any_photo_url",
64+
LocalDateTime.now(),
65+
null
66+
);
67+
var createUserJson = TestUtils.stringToMMF(createUserDTO);
68+
var createUserResponse = mvc.perform(
69+
MockMvcRequestBuilders.multipart("/signup/")
70+
.file(createUserJson)
71+
.contentType(MediaType.MULTIPART_FORM_DATA)
72+
.with(request -> {
73+
request.setMethod("POST");
74+
return request;
75+
})
76+
).andReturn().getResponse().getContentAsString();
77+
ResponseDTO response = TestUtils.jsonToObject(createUserResponse, ResponseDTO.class);
78+
assert response.getResource() != null;
79+
UserDTO userDTO = TestUtils.jsonToUserDTO(response.getResource().toString(), UserDTO.class);
80+
81+
var signInDTO = new SignInDTO(
82+
createUserDTO.getUsername(),
83+
createUserDTO.getPassword()
84+
);
85+
Cookie cookieAuthorization = mvc.perform(
86+
MockMvcRequestBuilders.post("/signin/")
87+
.contentType(MediaType.APPLICATION_JSON)
88+
.content(TestUtils.objectToJson(signInDTO))
89+
).andReturn().getResponse().getCookie("authorization");
90+
91+
assert cookieAuthorization != null;
92+
93+
CreatePostDTO post = new CreatePostDTO("any_content");
94+
95+
String createPostResponse = this.mvc.perform(MockMvcRequestBuilders.post("/post/")
96+
.cookie(cookieAuthorization)
97+
.content(TestUtils.objectToJson(post))
98+
.contentType(MediaType.APPLICATION_JSON)
99+
).andReturn().getResponse().getContentAsString();
100+
101+
ResponseDTO createdPostResponseDTO = TestUtils.jsonToObject(createPostResponse, ResponseDTO.class);
102+
assert createdPostResponseDTO.getResource() != null;
103+
104+
PostDTO createdPost = TestUtils.jsonToPostDTO(createdPostResponseDTO.getResource().toString(), PostDTO.class);
105+
106+
DeletePostDTO deletePostDTO = new DeletePostDTO(createdPost.getId().toString());
107+
108+
var deleteUserResponse = mvc.perform(
109+
MockMvcRequestBuilders.delete("/post/")
110+
.cookie(cookieAuthorization)
111+
.contentType(MediaType.APPLICATION_JSON)
112+
.content(TestUtils.objectToJson(deletePostDTO))
113+
).andReturn().getResponse();
114+
115+
int deleteUserResponseStatusCode = deleteUserResponse.getStatus();
116+
117+
assertThat(deleteUserResponseStatusCode).isEqualTo(204);
118+
}
119+
}

src/test/java/com/joaov1ct0r/restful_api_users_java/modules/utils/TestUtils.java

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@
33
import com.fasterxml.jackson.databind.ObjectMapper;
44
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
55
import com.joaov1ct0r.restful_api_users_java.modules.domain.dtos.ResponseDTO;
6+
import com.joaov1ct0r.restful_api_users_java.modules.posts.dtos.PostDTO;
7+
import com.joaov1ct0r.restful_api_users_java.modules.posts.entities.PostEntity;
8+
import com.joaov1ct0r.restful_api_users_java.modules.posts.mappers.PostMapper;
69
import com.joaov1ct0r.restful_api_users_java.modules.users.dtos.UserDTO;
710
import com.joaov1ct0r.restful_api_users_java.modules.users.entities.UserEntity;
811
import com.joaov1ct0r.restful_api_users_java.modules.users.mappers.UserMapper;
@@ -36,9 +39,34 @@ public static ResponseDTO jsonToObject(String json, Class<ResponseDTO> responseD
3639
}
3740
}
3841

42+
public static PostDTO jsonToPostDTO(String json, Class<PostDTO> postDTO) {
43+
try {
44+
String data = json.substring(json.indexOf("{") + 1, json.lastIndexOf("}"));
45+
46+
String[] parts = data.split(",\\s*");
47+
48+
String id = parts[0].split("=")[1];
49+
String content = parts[1].split("=")[1];
50+
String createdAt = parts[2].split("=")[1];
51+
String updatedAt = parts[3].split("=")[1];
52+
String userWhoCreatedId = parts[4].split("=")[1];
53+
54+
return PostMapper.toDTO(
55+
new PostEntity(
56+
UUID.fromString(id),
57+
content,
58+
LocalDateTime.parse(createdAt),
59+
LocalDateTime.parse(updatedAt),
60+
UUID.fromString(userWhoCreatedId)
61+
)
62+
);
63+
} catch (Exception e) {
64+
throw new RuntimeException(e.getMessage());
65+
}
66+
}
67+
3968
public static UserDTO jsonToUserDTO(String json, Class<UserDTO> userDTO) {
4069
try {
41-
System.out.println(userDTO);
4270
String data = json.substring(json.indexOf("{") + 1, json.lastIndexOf("}"));
4371

4472
String[] parts = data.split(",\\s*");

0 commit comments

Comments
 (0)