今天我們實作Users的CRUD,但今天因為花很多時間在前端的Header的排版,所以沒有什麼時間可以細作Users,
我們先根據Native Camp的會員頁和註冊頁來看大概需要什麼欄位後暫時先宣告好我們的schema。
Users.java 題外話lombok很好用,省了很多工
package com.mock.nativecamp.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "Users")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Users {
@Id
private String id;
private String name;
private String email;
private String password;
private String status;
private String coin;
private String timezone;
private String payMethod;
private String nextPayCheck;
private String ssoId;
}
然後就可以開始撰寫我們的controller和service了,controller主要是定義API接口,service則是做邏輯處理和Repository CRUD的呼叫。
由於時間關係我只做到Create User和Get all Users和Get one User。
UsersController.java
package com.mock.nativecamp.controller;
import com.mock.nativecamp.model.Users;
import com.mock.nativecamp.service.UsersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
@Slf4j
@RestController
@RequestMapping("/users")
public class UsersController {
private final UsersService usersService;
public UsersController(UsersService usersService) {
this.usersService = usersService;
}
/**
* Signup user
* @param user
* @return AdminUser
* @throws Exception
*/
@PostMapping(path = "/signup", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public Object SignupUser(@RequestBody Users user) throws Exception {
return usersService.signupUser(user);
}
/**
* Get all Users
* @return Users list
* @throws Exception
*/
@GetMapping(path = "/all", produces = MediaType.APPLICATION_JSON_VALUE)
public Object GetAllUsers() throws Exception {
return usersService.getAllUsers();
}
/**
* Get one user
* @return Users
* @throws Exception
*/
@GetMapping(path = "/user", produces = MediaType.APPLICATION_JSON_VALUE)
public Object GetUsers(@RequestParam String id) throws Exception {
return usersService.getUser(id);
}
}
因為只是簡單的測試是否可以操作存取MongoDB,尚未做邏輯檢查。
UsersService.java
package com.mock.nativecamp.service;
import com.mock.nativecamp.model.Users;
import com.mock.nativecamp.repository.UsersRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class UsersService {
@Autowired
private UsersRepository usersRepository;
public Object signupUser(Users user) {
usersRepository.save(user);
return new ResponseEntity(HttpStatus.ACCEPTED);
}
public Object getAllUsers() {
return usersRepository.findAll();
}
public Object getUser(String id) {
return usersRepository.findById(id);
}
}
然後運行起來使用postman來測試
新增使用者
取得使用者列表
取得單一使用者
下一篇應該是會把CRUD都給完成,然後透過網站end to end的確認邏輯後再來實作在service上。