Skip to content

Commit a44ba1b

Browse files
committed
feat(auto rest): simple sort
1 parent ef26e06 commit a44ba1b

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

README.md

+3-2
Original file line numberDiff line numberDiff line change
@@ -140,8 +140,9 @@ export default defineConfig({
140140
With this configuration, moquerie will automatically create RESTful endpoints for each resource types found with:
141141

142142
- `GET /resourceType`: list all instances
143-
- You can filter the results with query parameters, for example `GET /resourceType?name=foo`
144-
- You can paginate with `__page` (first page is `0`) and `__pageSize` (default `10`) query parameters: `GET /resourceType?__page=1&__pageSize=10`
143+
- Filter the results with query parameters, for example `GET /resourceType?name=foo`
144+
- Paginate with `__page` (first page is `0`) and `__pageSize` (default `10`) query parameters: `GET /resourceType?__page=1&__pageSize=10`
145+
- Sort with `__sort` query parameter with the syntax `<field>:asc` or `<field>:desc`: `GET /resourceType?__sort=name:asc`
145146
- `POST /resourceType`: create a new instance
146147
- `GET /resourceType/:id`: get an instance
147148
- `PUT /resourceType/:id`: update an instance

packages/core/src/rest/server.ts

+13
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,19 @@ export async function setupRestApi(mq: MoquerieInstance, expressApp: Application
226226

227227
data = await (ctx.db as UntypedQueryManagerProxy)[resourceType.name].findMany(predicate)
228228

229+
// Sort
230+
if (query.__sort != null) {
231+
const [key, order] = query.__sort.split(':')
232+
data = data.sort((a: any, b: any) => {
233+
const valueA = String(get(a, key))
234+
const valueB = String(get(b, key))
235+
if (order === 'asc') {
236+
return valueA.localeCompare(valueB)
237+
}
238+
return valueB.localeCompare(valueA)
239+
})
240+
}
241+
229242
// Pagination
230243
if (query.__page != null || query.__pageSize != null) {
231244
let page = 0

0 commit comments

Comments
 (0)