Skip to content

Commit c9e8276

Browse files
committed
feat: Generalizar a parte de filtros de pesquisa (#12).
1 parent 26b9021 commit c9e8276

File tree

15 files changed

+239
-214
lines changed

15 files changed

+239
-214
lines changed

src/main/java/br/com/virtuallibrary/commons/IConstants.java

+13
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ public interface IConstants {
1818
String BLANK = "";
1919
String SPACE = " ";
2020
String SEMICOLON = ";";
21+
String COLON = ":";
2122
String DOT = ".";
2223
String COMMA = ",";
2324
String HIFEN = "-";
@@ -32,4 +33,16 @@ public interface IConstants {
3233

3334
String BOOKS = IConstants.ROOT_URL + IConstants.V1 + "books";
3435
String RATINGS= IConstants.ROOT_URL + IConstants.V1 + "ratings";
36+
37+
// MONGODB
38+
String $AND = "$and";
39+
String $REGEX_CONTAINS = ".*%s.*";
40+
41+
String $CONTAINS = "contains";
42+
String $GREATER_THAN = "gt";
43+
String $GREATER_THAN_OR_EQUAL = "gte";
44+
String $LESS_THAN = "lt";
45+
String $LESS_THAN_OR_EQUAL = "lte";
46+
String $EQ = "eq";
3547
}
48+

src/main/java/br/com/virtuallibrary/commons/controllers/IBaseController.java

+3
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
import javax.validation.Valid;
77

8+
import org.springframework.data.web.PagedResourcesAssembler;
89
import org.springframework.hateoas.RepresentationModel;
910
import org.springframework.hateoas.server.mvc.RepresentationModelAssemblerSupport;
1011
import org.springframework.http.ResponseEntity;
@@ -26,6 +27,8 @@ public interface IBaseController<E extends BaseEntity, ID extends Serializable,
2627

2728
S getService();
2829

30+
PagedResourcesAssembler<E> getPagedResourcesAssembler();
31+
2932
RepresentationModelAssemblerSupport<E, M> getModelAssembler();
3033

3134
ResponseEntity<M> find(ID id);

src/main/java/br/com/virtuallibrary/commons/controllers/impl/BaseController.java

+39-1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@
55

66
import javax.validation.Valid;
77

8+
import org.springframework.data.web.PagedResourcesAssembler;
9+
import org.springframework.hateoas.CollectionModel;
10+
import org.springframework.hateoas.PagedModel;
811
import org.springframework.hateoas.RepresentationModel;
912
import org.springframework.hateoas.server.mvc.RepresentationModelAssemblerSupport;
1013
import org.springframework.http.HttpStatus;
@@ -16,6 +19,7 @@
1619
import org.springframework.web.bind.annotation.PostMapping;
1720
import org.springframework.web.bind.annotation.PutMapping;
1821
import org.springframework.web.bind.annotation.RequestBody;
22+
import org.springframework.web.bind.annotation.RequestParam;
1923
import org.springframework.web.bind.annotation.ResponseStatus;
2024

2125
import br.com.virtuallibrary.commons.IConstants;
@@ -40,22 +44,56 @@ public class BaseController<
4044

4145
private final S service;
4246
private final RepresentationModelAssemblerSupport<E, M> modelAssembler;
47+
private final PagedResourcesAssembler<E> pagedResourcesAssembler;
4348

44-
public BaseController(S service, RepresentationModelAssemblerSupport<E, M> modelAssembler) {
49+
public BaseController(S service, PagedResourcesAssembler<E> pagedResourcesAssembler, RepresentationModelAssemblerSupport<E, M> modelAssembler) {
4550
this.service = service;
4651
this.modelAssembler = modelAssembler;
52+
this.pagedResourcesAssembler = pagedResourcesAssembler;
4753
}
4854

4955
@Override
5056
public final S getService() {
5157
return service;
5258
}
5359

60+
@Override
61+
public PagedResourcesAssembler<E> getPagedResourcesAssembler() {
62+
return pagedResourcesAssembler;
63+
}
64+
5465
@Override
5566
public RepresentationModelAssemblerSupport<E, M> getModelAssembler() {
5667
return this.modelAssembler;
5768
}
5869

70+
@ResponseStatus(HttpStatus.OK)
71+
@GetMapping(produces = { IConstants.APPLICATION_JSON_UTF_8, IConstants.APPLICATION_XML_UTF_8 })
72+
@Operation(summary = "Retorna a lista de registros paginado.", description =
73+
"O filtro padrão é o igual ($eq), mas você pode utilizar:<br/>"
74+
+ "Contém - \"<b>contains</b>:valor\"<br/>"
75+
+ "Igual - \"<b>eq</b>:valor\"<br/>"
76+
+ "Maior que - \"<b>gt</b>:numerico\"<br/>"
77+
+ "Menor que - \"<b>lt</b>:numerico\"<br/>"
78+
+ "Maior ou igual - \"<b>gte</b>:numerico\"<br/>"
79+
+ "Menor ou igual - \"<b>lte</b>:numerico\"<br/>"
80+
+ "Também é possível combinar dois filtros - <b>gt</b>:numerico:<b>lt</b>:numerico")
81+
@ApiResponses(value = {
82+
@ApiResponse(responseCode = "200", description = "Registros listados com sucesso"),
83+
@ApiResponse(responseCode = "400", description = "Erro na obtenção dos dados ou filtro"),
84+
@ApiResponse(responseCode = "500", description = "Erro interno do servidor")})
85+
public ResponseEntity<CollectionModel<M>> findAll(
86+
@Parameter(description="Número da página.") @RequestParam(value = "page", required = false, defaultValue = IConstants.defaultPage) int page,
87+
@Parameter(description="Quantidade de registros por página.") @RequestParam(value = "size", required = false, defaultValue = IConstants.defaultSize) int size,
88+
@Parameter(description="Filtros de pesquisa conforme campos da entidade.") @RequestParam(required = false) Map<String,String> filters) {
89+
90+
PagedModel<M> collModel = null;
91+
92+
collModel = getPagedResourcesAssembler().toModel(getService().findPaginated(page, size, filters), getModelAssembler());
93+
94+
return ResponseEntity.ok().body(collModel);
95+
}
96+
5997
@Override
6098
@ResponseStatus(HttpStatus.OK)
6199
@GetMapping(value = "/{id}", produces = { IConstants.APPLICATION_JSON_UTF_8, IConstants.APPLICATION_XML_UTF_8 })

src/main/java/br/com/virtuallibrary/commons/services/IBaseService.java

+22-22
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import javax.validation.ValidationException;
99

1010
import org.springframework.data.domain.Page;
11+
import org.springframework.data.domain.Pageable;
1112
import org.springframework.data.mongodb.core.MongoTemplate;
1213
import org.springframework.data.mongodb.core.query.Criteria;
1314
import org.springframework.data.mongodb.core.query.Query;
@@ -20,39 +21,38 @@ public interface IBaseService<E extends BaseEntity, ID extends Serializable, R e
2021

2122
List<E> findAll();
2223

23-
/**
24-
* and – operador lógico AND
25-
* or – operador lógico OR
26-
* not – operador lógico NOT
27-
* gt = maior que
28-
* lt = menor que
29-
* gte = maior ou igual
30-
* lte = menor ou igual
31-
* ne = diferente de
32-
* in = todos os documentos cujo atributo possui um dos valores especificados (no SQL operador IN)
33-
* nin = todos os documentos cujo atributo não possui um dos valores especificados (no SQL operador NOT IN)
34-
* @param page A página a ser pesquisada.
35-
* @param size A quantidade de registro por página.
36-
* @return O resultado paginado.
37-
*/
38-
Page<E> findPaginated(int page, int size);
24+
Page<E> findPaginated(final int page, final int size);
3925

40-
Optional<E> findById(ID id);
26+
Page<E> findPaginated(int page, int size, Map<String, String> filters);
27+
28+
Page<E> findAll(Query query, int page, int size);
29+
30+
Page<E> findAll(Query query, int page, int size, List<Criteria> criterias);
31+
32+
Page<E> getPage(List<E> results, Pageable pageable, Query query, List<Criteria> criterias);
33+
34+
Optional<E> findById(final ID id);
4135

4236
Optional<E> save(E object);
4337

44-
void delete(ID id);
38+
void delete(final ID id);
4539

46-
Optional<E> update(Map<String, String> updates, ID id) throws ValidationException, SecurityException, IllegalArgumentException, IllegalAccessException;
40+
Optional<E> update(Map<String, String> updates, final ID id) throws ValidationException, SecurityException, IllegalArgumentException, IllegalAccessException;
4741

48-
Optional<E> update(E object, ID id);
42+
Optional<E> update(E object, final ID id);
4943

5044
UserDetails getUser();
5145

5246
MongoTemplate getTemplate();
5347

54-
Criteria getCriteriaByFilter(Query query, String filter, Object value);
48+
Map<String, String> getFilterValues(Map<String, String> filters);
5549

56-
Page<E> findAll(Query query, int page, int size);
50+
Criteria getCriteriaByFilter(Criteria criteria, String filter, Object value);
51+
52+
Criteria getCriteriaByFilter(Criteria criteria, String filter, Object value, String regex);
53+
54+
Criteria createCriteriaByFilter(Query query, String field, String value, String regex);
55+
56+
Criteria createCriteriaByFilter(Query query, String field, String value);
5757

5858
}

0 commit comments

Comments
 (0)