Skip to content

Commit 74ecdad

Browse files
committed
fix: fix buildSortBy issue when sort is undefined
1 parent db00c5f commit 74ecdad

File tree

1 file changed

+20
-9
lines changed

1 file changed

+20
-9
lines changed

src/Resource.ts

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,9 @@ export class Resource extends BaseResource {
2020

2121
private manager: ModelManager;
2222

23-
private propertiesObject: Record<string, any>;
23+
private propertiesObject: Record<string, Property>;
24+
25+
private idProperty: Property;
2426

2527
constructor(args: {
2628
model: DMMF.Model;
@@ -35,6 +37,7 @@ export class Resource extends BaseResource {
3537
this.enums = getEnums(clientModule);
3638
this.manager = this.client[lowerCase(model.name)];
3739
this.propertiesObject = this.prepareProperties();
40+
this.idProperty = this.properties().find((p) => p.isId())!;
3841
}
3942

4043
public databaseName(): string {
@@ -69,15 +72,18 @@ export class Resource extends BaseResource {
6972

7073
public async find(
7174
filter: Filter,
72-
params: Record<string, any> = {},
75+
params: {
76+
limit?: number;
77+
offset?: number;
78+
sort?: {
79+
sortBy?: string;
80+
direction?: 'asc' | 'desc';
81+
};
82+
} = {},
7383
): Promise<Array<BaseRecord>> {
7484
const { limit = 10, offset = 0, sort = {} } = params;
75-
const { direction, sortBy } = sort as {
76-
direction: 'asc' | 'desc';
77-
sortBy: string;
78-
};
7985

80-
const orderBy = this.buildSortBy(sortBy, direction);
86+
const orderBy = this.buildSortBy(sort);
8187
const results = await this.manager.findMany({
8288
where: convertFilter(this.model.fields, filter),
8389
skip: offset,
@@ -90,7 +96,12 @@ export class Resource extends BaseResource {
9096
);
9197
}
9298

93-
private buildSortBy(path: string, direction: 'asc' | 'desc') {
99+
private buildSortBy(sort: { sortBy?: string; direction?: 'asc' | 'desc' } = {}) {
100+
let { sortBy: path } = sort;
101+
const { direction = 'desc' } = sort;
102+
103+
if (!path) path = this.idProperty.path();
104+
94105
const [basePath, sortBy] = path.split('.');
95106
const sortByProperty = this.property(basePath);
96107

@@ -108,7 +119,7 @@ export class Resource extends BaseResource {
108119

109120
return {
110121
[basePath]: direction,
111-
}
122+
};
112123
}
113124

114125
public async findOne(id: string | number): Promise<BaseRecord | null> {

0 commit comments

Comments
 (0)