Skip to content

Commit

Permalink
fix: fix buildSortBy issue when sort is undefined
Browse files Browse the repository at this point in the history
  • Loading branch information
dziraf committed Feb 12, 2024
1 parent db00c5f commit 326b0b6
Showing 1 changed file with 20 additions and 9 deletions.
29 changes: 20 additions & 9 deletions src/Resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ export class Resource extends BaseResource {

private manager: ModelManager;

private propertiesObject: Record<string, any>;
private propertiesObject: Record<string, Property>;

private idProperty: Property;

constructor(args: {
model: DMMF.Model;
Expand All @@ -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())!;

Check warning on line 40 in src/Resource.ts

View workflow job for this annotation

GitHub Actions / Test

Forbidden non-null assertion

Check warning on line 40 in src/Resource.ts

View workflow job for this annotation

GitHub Actions / Test

Forbidden non-null assertion
}

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

public async find(
filter: Filter,
params: Record<string, any> = {},
params: {
limit?: number;
offset?: number;
sort?: {
sortBy?: string;
direction?: 'asc' | 'desc';
};
} = {},
): Promise<Array<BaseRecord>> {
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,
Expand All @@ -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);

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

return {
[basePath]: direction,
}
};
}

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

0 comments on commit 326b0b6

Please sign in to comment.