Skip to content

Commit

Permalink
Add custom order by fields to list generic endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
G4brym committed Jan 8, 2025
1 parent 2d353f4 commit 674aa74
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 6 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "chanfana",
"version": "2.5.2",
"version": "2.5.3",
"description": "OpenAPI 3 and 3.1 schema generator and validator for Hono, itty-router and more!",
"main": "dist/index.js",
"module": "dist/index.mjs",
Expand Down
2 changes: 1 addition & 1 deletion src/endpoints/d1/list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export class D1ListEndpoint<HandleArgs extends Array<object> = Array<object>> ex
where = `WHERE ${conditions.join(" AND ")}`;
}

let orderBy = `ORDER BY ${this.meta.model.primaryKeys[0]} DESC`;
let orderBy = `ORDER BY ${this.defaultOrderBy || this.meta.model.primaryKeys[0]} DESC`;
if (filters.options.order_by) {
orderBy = `ORDER BY ${filters.options.order_by} ${filters.options.order_by_direction || "ASC"}`;
}
Expand Down
17 changes: 13 additions & 4 deletions src/endpoints/list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ export class ListEndpoint<HandleArgs extends Array<object> = Array<object>> exte
searchFields?: Array<string>;
searchFieldName = "search";
optionFields = ["page", "per_page", "order_by", "order_by_direction"];
orderByFields = [];
defaultOrderBy?: string;

getSchema() {
const parsedQueryParameters = this.meta.fields
Expand All @@ -47,11 +49,18 @@ export class ListEndpoint<HandleArgs extends Array<object> = Array<object>> exte
});
}

const queryParameters = z
let queryParameters = z
.object({
page: z.number().int().min(1).optional().default(1),
per_page: z.number().int().min(1).max(100).optional().default(20),
order_by: Str({
})
.extend(parsedQueryParameters);

if (this.orderByFields && this.orderByFields.length > 0) {
queryParameters = queryParameters.extend({
order_by: Enumeration({
default: this.orderByFields[0],
values: this.orderByFields,
description: "Order By Column Name",
required: false,
}),
Expand All @@ -61,8 +70,8 @@ export class ListEndpoint<HandleArgs extends Array<object> = Array<object>> exte
description: "Order By Direction",
required: false,
}),
})
.extend(parsedQueryParameters);
});
}

return {
request: {
Expand Down

0 comments on commit 674aa74

Please sign in to comment.