Skip to content

Commit

Permalink
feat(auto rest): simple query filters
Browse files Browse the repository at this point in the history
  • Loading branch information
Akryum committed Sep 18, 2024
1 parent 5ea582e commit 9c9a922
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ export default defineConfig({
With this configuration, moquerie will automatically create RESTful endpoints for each resource types found with:

- `GET /resourceType`: list all instances
- You can filter the results with query parameters, for example `GET /resourceType?name=foo`
- `POST /resourceType`: create a new instance
- `GET /resourceType/:id`: get an instance
- `PUT /resourceType/:id`: update an instance
Expand Down
18 changes: 15 additions & 3 deletions packages/core/src/rest/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { pickRandom, repeat } from '../util/random.js'
import { getFactoryStorage } from '../factory/storage.js'
import { generateResourceInstances } from '../resource/generateInstances.js'
import { createResourceInstanceReference } from '../resource/resourceReference.js'
import { isPlainObject } from '../util/object.js'
import { get, isPlainObject } from '../util/object.js'
import { type HookBeforeSendResponseContext, hooks } from '../hooks.js'
import type { UntypedQueryManagerProxy } from '../resource/queryManagerProxy.js'

Expand Down Expand Up @@ -162,7 +162,7 @@ export async function setupRestApi(mq: MoquerieInstance, expressApp: Application

if (!mq.data.silent) {
// eslint-disable-next-line no-console
console.log(`[Auto REST] ${req.method} ${req.path}`, req.body)
console.log(`[Auto REST] ${req.method} ${req.path}`, 'query:', query, 'body:', req.body)
}

if (!resourceType) {
Expand Down Expand Up @@ -210,7 +210,19 @@ export async function setupRestApi(mq: MoquerieInstance, expressApp: Application
}
else {
if (req.method === 'GET') {
data = await (ctx.db as UntypedQueryManagerProxy)[resourceType.name].findMany()
const predicate = (data: any) => {
for (const key in query) {
if (key.startsWith('__')) {
continue
}
// eslint-disable-next-line eqeqeq
if (get(data, key) != query[key]) {
return false
}
}
return true
}
data = await (ctx.db as UntypedQueryManagerProxy)[resourceType.name].findMany(predicate)
}
if (req.method === 'POST') {
data = await (ctx.db as UntypedQueryManagerProxy)[resourceType.name].create(req.body)
Expand Down

0 comments on commit 9c9a922

Please sign in to comment.