今天我們來看一下Native Camp用戶設定,看一下有沒有遺漏什麼欄位沒有設置的,
這邊可以看到可修改的欄位有
果然根據可修改的資料,我們發現了有許多沒有觀察到的欄位需補充,生日、電子報、圖片路徑、國籍、居住地、不公開設定
更新後的Users.java
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
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;
}
我自己在今年開始寫Spring時,會習慣去建立request以及response的Object class,這樣在做欄位檢查以及統一管理很方便,再加上使用lombok整個很清爽簡單。
首先在payload資料夾中新增SignupReq.java
package com.mock.nativecamp.payload;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NonNull;
@Data
@AllArgsConstructor()
public class SignupReq {
@NonNull
private String name;
@NonNull
private String email;
@NonNull
private String password;
@NonNull
private String birthday;
@NonNull
private String gender;
@NonNull
private String credit_token;
}
然後將UsersController.java中的SignupUser @RequestBody改成SignupReq
@PostMapping(path = "/signup", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public Object SignupUser(@RequestBody SignupReq signupReq) throws Exception {
return usersService.signupUser(signupReq);
}
這樣只要request沒有帶任何一個@NonNull則會有error
Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `com.mock.nativecamp.payload.SignupReq`, problem: gender is marked non-null but is null; nested exception is com.fasterxml.jackson.databind.exc.ValueInstantiationException: Cannot construct instance of `com.mock.nativecamp.payload.SignupReq`, problem: gender is marked non-null but is null
at [Source: (PushbackInputStream); line: 6, column: 1]]
這邊錯誤可以看到沒有帶gender,這樣就可以對request data作保護,少帶必要欄位可以直接拋錯,這邊只要去做error handler就可以很方便的去管理,還有如果多帶其他不相關的欄位,因為Object沒有宣告,所以會直接忽略。
今天完成了users的欄位遺漏檢查以及新增了註冊時的request檢查,明天會繼續在完善Users的各種CRUD。