fix: error without filterableColumns. Added logger (#381)

This commit is contained in:
Robin De Schepper 2022-11-16 08:58:00 +01:00 committed by GitHub
parent 479b5dbaf9
commit bb38270b97
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 27 additions and 4 deletions

View File

@ -91,6 +91,12 @@ http://localhost:3000/cats?limit=5&page=2&sortBy=color:DESC&search=i&filter.age=
}
```
Array values for filter operators such as `$in` should be provided as comma-separated values:
```
http://localhost:3000/cats?filter.name=$in:George,Milo
```
#### Code
```ts
@ -292,3 +298,10 @@ const config: PaginateConfig<CatEntity> = {
const result = await paginate<CatEntity>(query, catRepo, config)
```
## Troubleshooting
The package does not report error reasons in the response bodies. They are instead
reported as `debug` level [logging](https://docs.nestjs.com/techniques/logger#logger).
Common errors include missing `sortableColumns` or `filterableColumns` (the latter only affects filtering).

View File

@ -16,12 +16,14 @@ import {
FindOptionsWhere,
} from 'typeorm'
import { PaginateQuery } from './decorator'
import { ServiceUnavailableException } from '@nestjs/common'
import { ServiceUnavailableException, Logger } from '@nestjs/common'
import { values, mapKeys } from 'lodash'
import { stringify } from 'querystring'
import { WherePredicateOperator } from 'typeorm/query-builder/WhereClause'
import { Column, Order, RelationColumn, SortBy } from './helper'
const logger: Logger = new Logger('nestjs-paginate')
export class Paginated<T> {
data: T[]
meta: {
@ -119,11 +121,16 @@ export function getFilterTokens(raw: string): string[] {
function parseFilter<T>(query: PaginateQuery, config: PaginateConfig<T>) {
const filter: { [columnName: string]: FindOperator<string> } = {}
let filterableColumns = config.filterableColumns
if (filterableColumns === undefined) {
logger.debug("No 'filterableColumns' given, ignoring filters.")
filterableColumns = {}
}
for (const column of Object.keys(query.filter)) {
if (!(column in config.filterableColumns)) {
if (!(column in filterableColumns)) {
continue
}
const allowedOperators = config.filterableColumns[column]
const allowedOperators = filterableColumns[column]
const input = query.filter[column]
const statements = !Array.isArray(input) ? [input] : input
for (const raw of statements) {
@ -197,7 +204,10 @@ export async function paginate<T>(
return !!entityColumns.find((c) => c === column)
}
if (config.sortableColumns.length < 1) throw new ServiceUnavailableException()
if (config.sortableColumns.length < 1) {
logger.debug("Missing required 'sortableColumns' config.")
throw new ServiceUnavailableException()
}
if (query.sortBy) {
for (const order of query.sortBy) {