Skip to content

Commit 5211dd7

Browse files
feat(postUser): create an endpoint for creating a new user (#28)
* feat(postUser): create an endpoint for creating a new user * feat(postUser): correction du rebase --------- Co-authored-by: Romain Vanhee <romain.vanhee@yrycom.com>
1 parent 64df086 commit 5211dd7

7 files changed

Lines changed: 150 additions & 13 deletions

File tree

README.md

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -257,6 +257,7 @@ Update an existing user's information.
257257
```http
258258
PUT /random-users/1
259259
Content-Type: application/json
260+
PUT /random-users/{id}
260261
```
261262

262263
**Request Body:**
@@ -272,6 +273,24 @@ Content-Type: application/json
272273
"nat": "FR"
273274
}
274275
```
276+
#### Create a new user
277+
```http
278+
POST /random-users
279+
```
280+
Example body:
281+
282+
```json
283+
{
284+
"gender": "female",
285+
"firstname": "Albert",
286+
"lastname": "Bing",
287+
"civility": "Mrs",
288+
"email": "albert.bing@example.com",
289+
"phone": "123456789",
290+
"picture": "pic.jpg",
291+
"nat": "FR"
292+
}
293+
```
275294

276295
**Responses:**
277296
- `200 OK` - User updated successfully
@@ -567,7 +586,7 @@ This project integrates with **Random User Generator API**:
567586
- [x] [Add this endpoint get /user/{id}](https://github.com/XPEHO/spring_boot_java_random_user/issues/8)
568587
- [x] [Add this endpoint put /user/{id}](https://github.com/XPEHO/spring_boot_java_random_user/issues/9)
569588
- [ ] [Add this endpoint delete /user/{id}](https://github.com/XPEHO/spring_boot_java_random_user/issues/10)
570-
- [ ] [Add this endpoint post /user](https://github.com/XPEHO/spring_boot_java_random_user/issues/11)
589+
- [x] [Add this endpoint post /user](https://github.com/XPEHO/spring_boot_java_random_user/issues/11)
571590

572591
---
573592

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package com.xpeho.spring_boot_java_random_user.domain.usecases;
2+
3+
import com.xpeho.spring_boot_java_random_user.domain.entities.UserEntity;
4+
import com.xpeho.spring_boot_java_random_user.domain.entities.UserRequest;
5+
import com.xpeho.spring_boot_java_random_user.domain.services.UserService;
6+
import org.springframework.stereotype.Service;
7+
8+
@Service
9+
public class CreateUserUseCase {
10+
private final UserService userService;
11+
12+
public CreateUserUseCase(UserService userService) {
13+
this.userService = userService;
14+
}
15+
16+
public UserEntity execute(UserRequest user) {
17+
UserEntity userToCreate = new UserEntity(
18+
null,
19+
user.gender(),
20+
user.firstname(),
21+
user.lastname(),
22+
user.civility(),
23+
user.email(),
24+
user.phone(),
25+
user.picture(),
26+
user.nat()
27+
);
28+
29+
return userService.save(userToCreate);
30+
}
31+
}

src/main/java/com/xpeho/spring_boot_java_random_user/presentation/controllers/UserController.java

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import org.springframework.web.bind.annotation.GetMapping;
1010
import org.springframework.web.bind.annotation.PathVariable;
1111
import org.springframework.web.bind.annotation.PutMapping;
12+
import org.springframework.web.bind.annotation.PostMapping;
1213
import org.springframework.web.bind.annotation.RequestBody;
1314
import org.springframework.web.bind.annotation.RequestMapping;
1415
import org.springframework.web.bind.annotation.RequestParam;
@@ -76,4 +77,16 @@ ResponseEntity<UserEntity> updateRandomUser(
7677
@RequestBody
7778
UserRequest user
7879
);
80+
81+
@PostMapping("")
82+
@Operation(
83+
summary = "Create a user",
84+
description = "Creates a new user in the database.",
85+
parameters = {
86+
@Parameter(name = "UserRequest", description = "User data to persist")
87+
}
88+
)
89+
@ApiResponse(responseCode = "201", description = "User successfully created")
90+
@ApiResponse(responseCode = "500", description = "Internal server error")
91+
ResponseEntity<UserEntity> createUser(@RequestBody UserRequest user);
7992
}

src/main/java/com/xpeho/spring_boot_java_random_user/presentation/handlers/UserHandler.java

Lines changed: 23 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import com.xpeho.spring_boot_java_random_user.domain.entities.UserEntity;
44
import com.xpeho.spring_boot_java_random_user.domain.entities.UserRequest;
55
import com.xpeho.spring_boot_java_random_user.domain.exceptions.UserNotFoundException;
6+
import com.xpeho.spring_boot_java_random_user.domain.usecases.CreateUserUseCase;
67
import com.xpeho.spring_boot_java_random_user.domain.usecases.FetchAndSaveRandomUsersUseCase;
78
import com.xpeho.spring_boot_java_random_user.domain.usecases.GetUserByIdUseCase;
89
import com.xpeho.spring_boot_java_random_user.domain.usecases.UpdateRandomUserUseCase;
@@ -11,6 +12,7 @@
1112
import org.slf4j.LoggerFactory;
1213
import org.springframework.http.HttpStatus;
1314
import org.springframework.http.ResponseEntity;
15+
import org.springframework.web.bind.annotation.RequestBody;
1416
import org.springframework.web.bind.annotation.RestController;
1517

1618
import java.io.IOException;
@@ -26,16 +28,21 @@ public class UserHandler implements UserController {
2628
private final FetchAndSaveRandomUsersUseCase fetchAndSaveRandomUsersUseCase;
2729
private final UpdateRandomUserUseCase updateRandomUserUseCase;
2830
private final GetUserByIdUseCase getUserByIdUseCase;
31+
private final CreateUserUseCase createUserUseCase;
2932

3033
public UserHandler(
3134
FetchAndSaveRandomUsersUseCase fetchAndSaveRandomUsersUseCase,
3235
UpdateRandomUserUseCase updateRandomUserUseCase,
33-
GetUserByIdUseCase getUserByIdUseCase
36+
GetUserByIdUseCase getUserByIdUseCase,
37+
CreateUserUseCase createUserUseCase
3438
) {
3539
this.fetchAndSaveRandomUsersUseCase = fetchAndSaveRandomUsersUseCase;
3640
this.updateRandomUserUseCase = updateRandomUserUseCase;
3741
this.getUserByIdUseCase = getUserByIdUseCase;
42+
this.createUserUseCase = createUserUseCase;
43+
3844
}
45+
3946

4047
@Override
4148
public ResponseEntity<List<UserEntity>> getRandomUsers(int count) {
@@ -59,15 +66,21 @@ public ResponseEntity<UserEntity> updateRandomUser(int id, UserRequest user) {
5966
}
6067
}
6168

62-
@Override
63-
public ResponseEntity<UserEntity> getUserById(int id) {
64-
try {
65-
UserEntity user = getUserByIdUseCase.execute(id);
66-
return ResponseEntity.ok(user);
67-
} catch (UserNotFoundException e) {
68-
logger.warn("warning: the requested user does not exist : {}", e.getMessage(), e);
69-
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
70-
}
69+
@Override
70+
public ResponseEntity<UserEntity> getUserById(int id) {
71+
try {
72+
UserEntity user = getUserByIdUseCase.execute(id);
73+
return ResponseEntity.ok(user);
74+
} catch (UserNotFoundException e) {
75+
logger.warn("warning: the requested user does not exist : {}", e.getMessage(), e);
76+
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
7177
}
78+
}
7279

80+
81+
@Override
82+
public ResponseEntity<UserEntity> createUser(@RequestBody UserRequest user) {
83+
UserEntity createdUser = createUserUseCase.execute(user);
84+
return ResponseEntity.status(HttpStatus.CREATED).body(createdUser);
85+
}
7386
}

src/test/java/com/xpeho/spring_boot_java_random_user/data/services/UserServiceImplTest.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,6 @@ void shouldSaveMappedUserAndReturnMappedDomainEntity() {
6565
UserEntity input = new UserEntity(3L, "female", "Alice", "Smith", "Mrs", "alice@smith.com", "5678", "new-pic.jpg", "US");
6666

6767
User daoToSave = new User();
68-
daoToSave.setId(3L);
6968
daoToSave.setFirstname("Alice");
7069

7170
User savedDao = new User();
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package com.xpeho.spring_boot_java_random_user.domain.usecases;
2+
3+
import com.xpeho.spring_boot_java_random_user.domain.entities.UserEntity;
4+
import com.xpeho.spring_boot_java_random_user.domain.entities.UserRequest;
5+
import com.xpeho.spring_boot_java_random_user.domain.services.UserService;
6+
import org.junit.jupiter.api.BeforeEach;
7+
import org.junit.jupiter.api.DisplayName;
8+
import org.junit.jupiter.api.Test;
9+
10+
import static org.junit.jupiter.api.Assertions.assertEquals;
11+
import static org.mockito.Mockito.mock;
12+
import static org.mockito.Mockito.verify;
13+
import static org.mockito.Mockito.when;
14+
15+
class CreateUserUseCaseTest {
16+
private UserService userService;
17+
private CreateUserUseCase useCase;
18+
19+
@BeforeEach
20+
void setUp() {
21+
userService = mock(UserService.class);
22+
useCase = new CreateUserUseCase(userService);
23+
}
24+
25+
@Test
26+
@DisplayName("Should create a user without keeping the input id")
27+
void shouldCreateUserWithoutKeepingInputId() {
28+
UserRequest payload = new UserRequest(
29+
"female", "Alice", "Smith", "Mrs", "alice@smith.com", "5678", "new-pic.jpg", "US"
30+
);
31+
UserEntity createdUser = new UserEntity(
32+
1L, "female", "Alice", "Smith", "Mrs", "alice@smith.com", "5678", "new-pic.jpg", "US"
33+
);
34+
UserEntity expectedSavedUser = new UserEntity(
35+
null, "female", "Alice", "Smith", "Mrs", "alice@smith.com", "5678", "new-pic.jpg", "US"
36+
);
37+
38+
when(userService.save(expectedSavedUser)).thenReturn(createdUser);
39+
40+
UserEntity result = useCase.execute(payload);
41+
42+
assertEquals(createdUser, result);
43+
verify(userService).save(expectedSavedUser);
44+
}
45+
}

src/test/java/com/xpeho/spring_boot_java_random_user/presentation/UserHandlerTest.java

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import com.xpeho.spring_boot_java_random_user.domain.entities.UserEntity;
44
import com.xpeho.spring_boot_java_random_user.domain.entities.UserRequest;
55
import com.xpeho.spring_boot_java_random_user.domain.exceptions.UserNotFoundException;
6+
import com.xpeho.spring_boot_java_random_user.domain.usecases.CreateUserUseCase;
67
import com.xpeho.spring_boot_java_random_user.domain.usecases.FetchAndSaveRandomUsersUseCase;
78
import com.xpeho.spring_boot_java_random_user.domain.usecases.GetUserByIdUseCase;
89
import com.xpeho.spring_boot_java_random_user.domain.usecases.UpdateRandomUserUseCase;
@@ -29,14 +30,16 @@ class UserHandlerTest {
2930
private FetchAndSaveRandomUsersUseCase fetchAndSaveRandomUsersUseCase;
3031
private UpdateRandomUserUseCase updateRandomUserUseCase;
3132
private GetUserByIdUseCase getUserByIdUseCase;
33+
private CreateUserUseCase createUserUseCase;
3234
private UserHandler userHandler;
3335

3436
@BeforeEach
3537
void setUp() {
3638
fetchAndSaveRandomUsersUseCase = mock(FetchAndSaveRandomUsersUseCase.class);
3739
updateRandomUserUseCase = mock(UpdateRandomUserUseCase.class);
3840
getUserByIdUseCase = mock(GetUserByIdUseCase.class);
39-
userHandler = new UserHandler(fetchAndSaveRandomUsersUseCase, updateRandomUserUseCase, getUserByIdUseCase);
41+
createUserUseCase = mock(CreateUserUseCase.class);
42+
userHandler = new UserHandler(fetchAndSaveRandomUsersUseCase, updateRandomUserUseCase, getUserByIdUseCase, createUserUseCase);
4043
}
4144

4245
@Test
@@ -117,4 +120,18 @@ void shouldReturnNotFoundWhenUpdateRandomUserFails() {
117120
assertNull(response.getBody());
118121
verify(updateRandomUserUseCase, times(1)).execute(123, request);
119122
}
123+
124+
@Test
125+
@DisplayName("Should return 201 and created user when createUser succeeds")
126+
void shouldReturnCreatedWhenCreateUserSucceeds() {
127+
UserRequest request = new UserRequest("female", "Emma", "Stone", "Ms", "emma@example.com", "0644444444", "emma.jpg", "FR");
128+
UserEntity created = new UserEntity(10L, "female", "Emma", "Stone", "Ms", "emma@example.com", "0644444444", "emma.jpg", "FR");
129+
when(createUserUseCase.execute(request)).thenReturn(created);
130+
131+
ResponseEntity<UserEntity> response = userHandler.createUser(request);
132+
133+
assertEquals(HttpStatus.CREATED, response.getStatusCode());
134+
assertEquals(created, response.getBody());
135+
verify(createUserUseCase, times(1)).execute(request);
136+
}
120137
}

0 commit comments

Comments
 (0)