Skip to content

Commit

Permalink
feat(auto rest): pagination
Browse files Browse the repository at this point in the history
  • Loading branch information
Akryum committed Sep 18, 2024
1 parent 9c9a922 commit ef26e06
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@ With this configuration, moquerie will automatically create RESTful endpoints fo

- `GET /resourceType`: list all instances
- You can filter the results with query parameters, for example `GET /resourceType?name=foo`
- You can paginate with `__page` (first page is `0`) and `__pageSize` (default `10`) query parameters: `GET /resourceType?__page=1&__pageSize=10`
- `POST /resourceType`: create a new instance
- `GET /resourceType/:id`: get an instance
- `PUT /resourceType/:id`: update an instance
Expand Down
15 changes: 15 additions & 0 deletions packages/core/src/rest/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,7 @@ export async function setupRestApi(mq: MoquerieInstance, expressApp: Application
}
else {
if (req.method === 'GET') {
// Query filters
const predicate = (data: any) => {
for (const key in query) {
if (key.startsWith('__')) {
Expand All @@ -222,7 +223,21 @@ export async function setupRestApi(mq: MoquerieInstance, expressApp: Application
}
return true
}

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

// Pagination
if (query.__page != null || query.__pageSize != null) {
let page = 0
if (query.__page != null) {
page = Number.parseInt(query.__page)
}
let pageSize = 10
if (query.__pageSize != null) {
pageSize = Number.parseInt(query.__pageSize)
}
data = data.slice(page * pageSize, (page + 1) * pageSize)
}
}
if (req.method === 'POST') {
data = await (ctx.db as UntypedQueryManagerProxy)[resourceType.name].create(req.body)
Expand Down

0 comments on commit ef26e06

Please sign in to comment.