Controller Response With Headers and List From Service From Custom Query In ReactiveCrudRepository

Viewed 10

What i would like to achieve is to have a response that has both headers and a list from the database as one response. I am using ReactiveCrudRepository.

Below is my Entity Car class


import lombok.Getter;
import lombok.Setter;
import org.springframework.data.annotation.Id;
import org.springframework.data.relational.core.mapping.Column;
import org.springframework.data.relational.core.mapping.Table;

import java.io.Serializable;

@Getter
@Setter
@Table("tbl_cars")
public class Car implements Serializable{

    @Column("price")
    private int price;

    @Column("model")
    private String model;

    @Id
    @Column("id")
    private int id;

    @Column("cylinders")
    private String cylinders;

    @Column("manufacturer")
    private String manufacturer;


}

Below is how i am currently finding the list of all the cars and also a list of cars by number of cylinders in my CarRepository that extends ReactiveCrudRepository<Car, Long>


    @Query("SELECT * FROM tbl_cars t where t.cylinders = :cylinderNo")
    Flux<Car> findByCylinders(String cylinderNo);

    Flux<Car> findAll();

Below is how the methods in my Controller look like

    @GetMapping("/get-all-cars")
    public Flux<Car> getAllCars(){
        return carRepository.findAll();
    }

    @GetMapping("/get-all-cars-by-cylinders")
    public Flux<Car> getAllCarsByCylinders(){
        return carRepository.findByCylinders("6");
    }

This is all working well but i am introducing a service which will have a method that is called processCars and will return Mono<ResponseEntity<MyCustomResponse>> which is supposed to have headers and also the list of cars by cylinders

I am stuck below where i am supposed to get findByCylinders from CarRepository and convert it to a list.

Below is what i am trying but its returning an empty list []


        List<Car> carList = new ArrayList<>();
        this.carRepository.findByCylinders("6")
                .collectList().subscribe(carList::addAll);

Below is how i should add the carList to my Mono response


return Mono.just(new ResponseEntity<>(MyCustomResponse.format("ok", 200, carList)));


And Below is how the my get method for processed cars should look like in Controller

    @PostMapping("/get-all-cars-by-cylinders")
    public Mono<ResponseEntity<MyCustomResponse>> getProcessedCars(@RequestHeader HttpHeaders httpHeaders,
                                                         @Valid @RequestBody MyRequest myRequest) {
        return apiService.processCars(httpHeaders, myRequest);
    }

How can i have the list from findByCylinders in my service

0 Answers
Related