Skip to content

Commit ef26e06

Browse files
committed
feat(auto rest): pagination
1 parent 9c9a922 commit ef26e06

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,7 @@ With this configuration, moquerie will automatically create RESTful endpoints fo
141141

142142
- `GET /resourceType`: list all instances
143143
- 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`
144145
- `POST /resourceType`: create a new instance
145146
- `GET /resourceType/:id`: get an instance
146147
- `PUT /resourceType/:id`: update an instance

packages/core/src/rest/server.ts

+15
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,7 @@ export async function setupRestApi(mq: MoquerieInstance, expressApp: Application
210210
}
211211
else {
212212
if (req.method === 'GET') {
213+
// Query filters
213214
const predicate = (data: any) => {
214215
for (const key in query) {
215216
if (key.startsWith('__')) {
@@ -222,7 +223,21 @@ export async function setupRestApi(mq: MoquerieInstance, expressApp: Application
222223
}
223224
return true
224225
}
226+
225227
data = await (ctx.db as UntypedQueryManagerProxy)[resourceType.name].findMany(predicate)
228+
229+
// Pagination
230+
if (query.__page != null || query.__pageSize != null) {
231+
let page = 0
232+
if (query.__page != null) {
233+
page = Number.parseInt(query.__page)
234+
}
235+
let pageSize = 10
236+
if (query.__pageSize != null) {
237+
pageSize = Number.parseInt(query.__pageSize)
238+
}
239+
data = data.slice(page * pageSize, (page + 1) * pageSize)
240+
}
226241
}
227242
if (req.method === 'POST') {
228243
data = await (ctx.db as UntypedQueryManagerProxy)[resourceType.name].create(req.body)

0 commit comments

Comments
 (0)