Restful : multiple cases for a same ressource (sam

2019-08-17 09:01发布

问题:

For example, i have two scenarios for creating a user :

  • Created by administrator, without password. The user will have to choose it on activation page.
  • Created by the user himself, with password. The activation page won't show password inputs because the password already exists.

The thing is it's the same resource, a user. But depending on who (where) the api is called, the expected behaviour is different.

In one case the DTO should contains the password posted by the user, in the other case it shouldn't.

What should i do ?

  • Two api end point with two differents DTO (with and without password) ? But we don't respect the convention that say one end point for creating a given resource
  • Same end point but the DTO received will contain the discriminant to know if we want to handle password or not ? If not, password field must be empty ?
  • Something else ?

I'm not sure how to do this right.

Thank you

回答1:

The best strategy for this situation is passing one attribute in the header of the request. With this information, you can create 2 endpoints using the attribute to direct the request.

Ex:

@PreAuthorize("hasRole('ROLE_USER')")
@PostMapping(headers = "X-YOUR-ORIGIN=user")
public ResponseEntity createUserByUser(){
   ...
}

@PreAuthorize("hasRole('ROLE_ADMIN')")
@PostMapping(headers = "X-YOUR-ORIGIN=admin")
public ResponseEntity createUserByAdmin(){
   ...
}


回答2:

I think the best way would be to make one end point, with an optional parameter. Something like:

@PostMapping public ResponseEntity createUser(@RequestParam(name = "userType") String userType){ //If it's admin, make sure the pwd is set in the dto. Else, it can be null }