From 326b0b624b5634ecca0bc612ba9672ad0ff6c578 Mon Sep 17 00:00:00 2001 From: Rafal Dziegielewski Date: Mon, 12 Feb 2024 16:49:18 +0100 Subject: [PATCH] fix: fix buildSortBy issue when sort is undefined --- src/Resource.ts | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/src/Resource.ts b/src/Resource.ts index 0b19500..1e9a84b 100644 --- a/src/Resource.ts +++ b/src/Resource.ts @@ -20,7 +20,9 @@ export class Resource extends BaseResource { private manager: ModelManager; - private propertiesObject: Record; + private propertiesObject: Record; + + private idProperty: Property; constructor(args: { model: DMMF.Model; @@ -35,6 +37,7 @@ export class Resource extends BaseResource { this.enums = getEnums(clientModule); this.manager = this.client[lowerCase(model.name)]; this.propertiesObject = this.prepareProperties(); + this.idProperty = this.properties().find((p) => p.isId())!; } public databaseName(): string { @@ -69,15 +72,18 @@ export class Resource extends BaseResource { public async find( filter: Filter, - params: Record = {}, + params: { + limit?: number; + offset?: number; + sort?: { + sortBy?: string; + direction?: 'asc' | 'desc'; + }; + } = {}, ): Promise> { const { limit = 10, offset = 0, sort = {} } = params; - const { direction, sortBy } = sort as { - direction: 'asc' | 'desc'; - sortBy: string; - }; - const orderBy = this.buildSortBy(sortBy, direction); + const orderBy = this.buildSortBy(sort); const results = await this.manager.findMany({ where: convertFilter(this.model.fields, filter), skip: offset, @@ -90,7 +96,12 @@ export class Resource extends BaseResource { ); } - private buildSortBy(path: string, direction: 'asc' | 'desc') { + private buildSortBy(sort: { sortBy?: string; direction?: 'asc' | 'desc' } = {}) { + let { sortBy: path } = sort; + const { direction = 'desc' } = sort; + + if (!path) path = this.idProperty.path(); + const [basePath, sortBy] = path.split('.'); const sortByProperty = this.property(basePath); @@ -108,7 +119,7 @@ export class Resource extends BaseResource { return { [basePath]: direction, - } + }; } public async findOne(id: string | number): Promise {