Home > Mobile >  How can take value request DTOs in my service @PutMapping
How can take value request DTOs in my service @PutMapping

Time:09-17

I'm trying to do an @PutMapping where I would put all the logic to change the attributes inside the service but I ran into a problem. How could I get the values from my requestDTO to play inside the class and make these changes inside the service and not in the controller?

The request data is the same as the response and class

private Long id;


private String program;

my controller and service implements

 @PutMapping(value = "/edit-program/test/{id}")
    public ResponseEntity<ProgramResponseDto> updateProgramByIdTest (
            @PathVariable(value = "id") final Long id,
            @Valid @RequestBody final ProgramRequestDto programRequestDto) throws UpdateDataException {

        ProgramResponseDto programResponseDto = ProgramMapper.INSTANCE.programToProgramResponseDTO(
                programService.Update(id));

        log.info(LocaleContext.format("response.success",
                (new Object() {
                }.getClass().getEnclosingMethod().getName()),
                HttpStatus.OK.toString()));

                return status(HttpStatus.OK).body(programResponseDto);

    }

  @Override
    public Program Update(Long id) throws UpdateDataException {

    Program program = null;

    try {

        Optional<Program> programDB = programRepository.findById(id);

        if (programDB.isPresent()) {

            program = programDB.get();

            ProgramRequestDto programRequestDto = ProgramRequestDto.builder().build();
            program.setProgram(programRequestDto.getProgram());
            program.setId(programRequestDto.getId());

            return programRepository.save(program);
        }
    } catch (Exception e){
        throw new UpdateDataException(e.getMessage());

    }
    return null;
}

service Program Update(Long id) throws UpdateDataException;

CodePudding user response:

Change the signature of the Service method to accept ProgramRequestDto as follows:

public Program Update(ProgramRequestDto programRequestDto) throws UpdateDataException

And update the Controller accordingly:

@PutMapping(value = "/edit-program/test/{id}")
public ResponseEntity<ProgramResponseDto> updateProgramByIdTest (
         @PathVariable(value = "id") final Long id,
         @Valid @RequestBody final ProgramRequestDto programRequestDto) throws UpdateDataException {

     ProgramResponseDto programResponseDto = ProgramMapper.INSTANCE.programToProgramResponseDTO(
             programService.Update(programRequestDto));

     log.info(LocaleContext.format("response.success",
             (new Object() {}.getClass().getEnclosingMethod().getName()),
             HttpStatus.OK.toString()));

     return status(HttpStatus.OK).body(programResponseDto);
}

Not sure if this is what you want but it is what I understood from your question.

  • Related