How to reduce Page return fields in an API?

Asked

Viewed 91 times

-1

I am implementing pagination in some endpoints of my API and the return is a Page. This object returns many arguments, there is some way to eliminate some of them?

The Repository extends Jparepository

SERVICE

@Autowired
ClienteRepositoy clienteRepositoy;

public List<Cliente> findAllList() {
    return clienteRepositoy.findAll();
}

CONTROLLER

@Autowired
ServiceCliente serviceCliente;

@GetMapping("/clientes")
public Page<Cliente> getClientes() {
    List<Cliente> clientes = serviceCliente.findAllList();
    return new PageImpl<>(convertToDto(clientes), PageRequest.of(0, 10), clientes.size());
}

RETURN JSON

{
    "content": [
        {
            "id": 1,
            "nome": "TESTE AUTOMATICO"
        }
    ],
    "pageable": {
        "sort": {
            "sorted": false,
            "unsorted": true,
            "empty": true
        },
        "offset": 0,
        "pageNumber": 0,
        "pageSize": 10,
        "paged": true,
        "unpaged": false
    },
    "totalPages": 1,
    "totalElements": 7,
    "last": true,
    "size": 10,
    "number": 0,
    "sort": {
        "sorted": false,
        "unsorted": true,
        "empty": true
    },
    "first": true,
    "numberOfElements": 7,
    "empty": false
}

I would like to remove information like the whole pageable object, for example:

"pageable": {
        "sort": {
            "sorted": false,
            "unsorted": true,
            "empty": true
        },
        "offset": 0,
        "pageNumber": 0,
        "pageSize": 10,
        "paged": true,
        "unpaged": false
    },

1 answer

0

I believe that the way you are doing is not ideal: you search all and then page them. In my view the right would be to fetch all paged: the findAll spring can receive a Peageable as parameter. This way you would not return a PageImpl<>, you would have to return from your service method a Page; That way, having a Page list, you can return only the content of that list (a customer list really): return clientes.getContent(). I hope I made myself clear. Hug!

  • You were very clear. I return a list of customers and do a processing with that list before returning, as well as convert them to DTO not to expose my entity directly. If I use the findAll(Pageable) I’ll have to work with Pages and not with entities.

  • And the return turns out to be the same as the way I’m doing it :/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.