挑戰目標: MockNative Camp
今天來做教師的更新API,因為我沒有實際看過教師更新的畫面,所以這邊就簡單的來更新一些欄位示範,基本上其餘欄位也只是複製到payload中的patchreq object就可以了。
PatchReq.java 密碼跟信箱一樣是要用其他方式去做更新,所以這邊並不列入可更新範圍
package com.mock.nativecamp.payload.teacher;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NonNull;
@Data
@AllArgsConstructor()
public class PatchReq {
@NonNull
private String firstName;
private String middleName;
@NonNull
private String lastName;
@NonNull
private String birthday;
private String referrerEmail;
@NonNull
private String country;
@NonNull
private String nationality;
}
TeachersController.java 這邊只貼新增的code
@PatchMapping(path = "/patch/{userId}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public Object patchTeacher(@PathVariable("userId") String userId, @RequestBody PatchReq patchReq) {
return teachersServer.updateTeacher(userId, patchReq);
}
Teachers.java teacher object 新增update method
public Teachers updateTeacher(Teachers teacher, PatchReq patchReq) {
teacher.setFirstName(patchReq.getFirstName());
if (patchReq.getMiddleName() != null) {
teacher.setMiddleName(patchReq.getMiddleName());
}
teacher.setLastName(patchReq.getLastName());
teacher.setBirthday(patchReq.getBirthday());
if (teacher.getReferrerEmail() == null & patchReq.getReferrerEmail() != null) {
teacher.setReferrerEmail(patchReq.getReferrerEmail());
}
teacher.setCountry(patchReq.getCountry());
teacher.setNationality(patchReq.getNationality());
return teacher;
}
TeachersServer.java 這邊做了先查詢在更新,加入檢查是否有此紀錄,沒有的話回傳404並log
public Object updateTeacher(String userId, PatchReq patchReq) {
Teachers teacher = teachersRepository.findByUserId(userId);
if (teacher == null) {
log.error(String.format("Teacher not found id: %s", userId));
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
teacher.updateTeacher(teacher, patchReq);
teachersRepository.save(teacher);
return new ResponseEntity(HttpStatus.ACCEPTED);
}
沒有找到紀錄
log 顯示,然後可以看到用了AOP攔截並log request跟response後,不用額外加code,真的很方便。
成功更新教師資料
查看教師資料
接下來繼續Mock也只是重複的新增model、controller、service的CRUD,前端那邊看起來要串接應該還要很久,甚至來不及串接,我會思考剩下的時間要不要轉向其他方向,像是一些全局性error handling 或者是部署更甚至是socket以及WebRTC的實作。