Home > OS >  Spring - Return string result of endpoint and storing it on a variable
Spring - Return string result of endpoint and storing it on a variable

Time:10-26

This is my endpoint and it returns me my email address when logged in

@GetMapping("/user")
public String userInfo(Authentication authentication) {
    String userName = authentication.getName();
    return userName;
}

I want to give the createdBy variable this value

@PostMapping("/request")
public RequestDTO saveRequest(@RequestBody final RequestDTO requestDTO) {
    requestDTO.setCreatedBy(InsertTheNewStringVariableHere);
    return requestUseCase.createRequest(requestDTO);
}

CodePudding user response:

Assuming you have authentication in both endpoints you can simply add Authentication as a parameter in the second endpoint:

@PostMapping("/request")
public RequestDTO saveRequest(@RequestBody final RequestDTO requestDTO, 
                              Authentication authentication) {
    requestDTO.setCreatedBy(authentication.getName());
    return requestUseCase.createRequest(requestDTO);
}

CodePudding user response:

Its all depend on how your access your rest api.

If you own the code, I mean if your classes are in the same project, you can do this:

@PostMapping("/request")
public RequestDTO saveRequest(@RequestBody final RequestDTO requestDTO) {
    requestDTO.setCreatedBy(yourServiceInstance.userInfo(authentication));
    return requestUseCase.createRequest(requestDTO);
}

If it is an external api, you will have to call the service from a http client:

@PostMapping("/request")
public RequestDTO saveRequest(@RequestBody final RequestDTO requestDTO) {
    requestDTO.setCreatedBy(yourHttpClient.callUserInfo(authentication));
    return requestUseCase.createRequest(requestDTO);
}

You will inject your userInfo object and a Authentication object in your class.

  • Related