From bb38270b97b160447b8b5caac446197d8722bd0a Mon Sep 17 00:00:00 2001 From: Robin De Schepper Date: Wed, 16 Nov 2022 08:58:00 +0100 Subject: [PATCH] fix: error without filterableColumns. Added logger (#381) --- README.md | 13 +++++++++++++ src/paginate.ts | 18 ++++++++++++++---- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index ce052e1..260b0ff 100644 --- a/README.md +++ b/README.md @@ -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 = { const result = await paginate(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). diff --git a/src/paginate.ts b/src/paginate.ts index 935feed..fc9c854 100644 --- a/src/paginate.ts +++ b/src/paginate.ts @@ -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 { data: T[] meta: { @@ -119,11 +121,16 @@ export function getFilterTokens(raw: string): string[] { function parseFilter(query: PaginateQuery, config: PaginateConfig) { const filter: { [columnName: string]: FindOperator } = {} + 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( 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) {