挑戰目標: MockNative Camp後端
昨天寫了signup的request object,但因為我們UsersRepository無法直接使用SignupReq Object,所以我自己是會在Users.java中寫轉換的code,雖然有點蠢但我之前找了滿久沒有看到比較好的解決方法,如果看到剛好看到文章又剛好知道怎麼優化的麻煩留個言告訴我~
User.java
package com.mock.nativecamp.model;
import com.mock.nativecamp.payload.user.SignupReq;
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;
private String gender;
private String creditToken;
private String profilePic;
private boolean news;
private String birthday;
private String userNationality;
private String userResidence;
private boolean genderNotify;
private boolean birthdayNotify;
private boolean userNationalityNotify;
private boolean userResidenceNotify;
public Users signUser(SignupReq signupReq) {
Users user = new Users();
user.setName(signupReq.getName());
user.setEmail(signupReq.getEmail());
user.setPassword(signupReq.getPassword());
user.setBirthday(signupReq.getBirthday());
user.setGender(signupReq.getGender());
user.setCreditToken(signupReq.getCredit_token());
return user;
}
}
然後將我們的UsersService.java修改一下
package com.mock.nativecamp.service;
import com.mock.nativecamp.model.Users;
import com.mock.nativecamp.payload.user.SignupReq;
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(SignupReq signupReq) {
Users user = new Users().signUser(signupReq);
usersRepository.save(user);
return new ResponseEntity(HttpStatus.ACCEPTED);
}
public Object getAllUsers() {
return usersRepository.findAll();
}
public Object getUser(String id) {
return usersRepository.findById(id);
}
}
我們使用postman來測試一下
新增user
取得所有User
取得單一User
明天繼續新增patch user的request object和一樣的在Users.java中新增轉換method。