REST、MVC - link 应该在哪一层创建资源?
REST, MVC - In which layer should link creation for Resources happen?
以下是我的场景的抽象案例。
在通过 /customers/:id
端点发出 GET
请求后, 控制器 中的 Request Handler
从 Service 其中 returns 具有指定 id 的 Customer
。之后,在 Controller 中,接收到的 Customer
被转换为 CustomerResourceDTO
.
@GetMapping("customers/{id}")
public ResponseEntity<CourseResourceDTO> getSingleCustomer(@PathVariable int id) {
Customer customer = customerService.getSingleCustomer(id);
CustomerResourceDTO customerResourceDTO = new CustomerResourceDTO(customer);
return new ResponseEntity<>(courseResourceDTO, HttpStatus.OK);
}
并且在 CustomerResourceDTO
构造函数中,还创建了链接。
@Getter @Setter
public class CustomerResourceDTO extends ResourceSupport {
String firstName;
String lastName;
public CustomerResourceDTO (Customer customer) {
this.firstName = customer.firstName;
this.lastName = customer.lastName;
add(new Link("https://linkToSelf").withSelfRel());
}
}
在 DTO/Resource 创建中设置链接是一个好习惯,还是我应该将其委托给另一个 class/layer?
从富领域模型的角度来看;我将以下 方法 添加到扩展 ResourceSupport 的 DTO:addSelfLink
和 addLink
(添加 link 到另一个资源),否则,在我看来,他们应该在 Service 中找到一个位置,并在 Controller.
以下是我的场景的抽象案例。
在通过 /customers/:id
端点发出 GET
请求后, 控制器 中的 Request Handler
从 Service 其中 returns 具有指定 id 的 Customer
。之后,在 Controller 中,接收到的 Customer
被转换为 CustomerResourceDTO
.
@GetMapping("customers/{id}")
public ResponseEntity<CourseResourceDTO> getSingleCustomer(@PathVariable int id) {
Customer customer = customerService.getSingleCustomer(id);
CustomerResourceDTO customerResourceDTO = new CustomerResourceDTO(customer);
return new ResponseEntity<>(courseResourceDTO, HttpStatus.OK);
}
并且在 CustomerResourceDTO
构造函数中,还创建了链接。
@Getter @Setter
public class CustomerResourceDTO extends ResourceSupport {
String firstName;
String lastName;
public CustomerResourceDTO (Customer customer) {
this.firstName = customer.firstName;
this.lastName = customer.lastName;
add(new Link("https://linkToSelf").withSelfRel());
}
}
在 DTO/Resource 创建中设置链接是一个好习惯,还是我应该将其委托给另一个 class/layer?
从富领域模型的角度来看;我将以下 方法 添加到扩展 ResourceSupport 的 DTO:addSelfLink
和 addLink
(添加 link 到另一个资源),否则,在我看来,他们应该在 Service 中找到一个位置,并在 Controller.