fix: _embed param

This commit is contained in:
typicode
2024-01-12 01:09:16 +01:00
parent a4d829ab52
commit a4dda8ec64
2 changed files with 24 additions and 8 deletions

View File

@@ -54,8 +54,10 @@ await new Promise<void>((resolve, reject) => {
await test('createApp', async (t) => {
// URLs
const POSTS = '/posts'
const POSTS_WITH_COMMENTS = '/posts?_embed=comments'
const POST_1 = '/posts/1'
const POST_NOT_FOUND = '/posts/-1'
const POST_WITH_COMMENTS = '/posts/1?_embed=comments'
const COMMENTS = '/comments'
const POST_COMMENTS = '/comments?postId=1'
const NOT_FOUND = '/not-found'
@@ -73,8 +75,10 @@ await test('createApp', async (t) => {
// API
{ method: 'GET', url: POSTS, statusCode: 200 },
{ method: 'GET', url: POSTS_WITH_COMMENTS, statusCode: 200 },
{ method: 'GET', url: POST_1, statusCode: 200 },
{ method: 'GET', url: POST_NOT_FOUND, statusCode: 404 },
{ method: 'GET', url: POST_WITH_COMMENTS, statusCode: 200 },
{ method: 'GET', url: COMMENTS, statusCode: 200 },
{ method: 'GET', url: POST_COMMENTS, statusCode: 200 },
{ method: 'GET', url: OBJECT, statusCode: 200 },

View File

@@ -47,6 +47,10 @@ export type PaginatedItems = {
data: Item[]
}
function ensureArray(arg: string | string[] = []): string[] {
return Array.isArray(arg) ? arg : [arg]
}
function embed(db: Low<Data>, name: string, item: Item, related: string): Item {
if (inflection.singularize(related) === related) {
const relatedData = db.data[inflection.pluralize(related)] as Item[]
@@ -148,13 +152,13 @@ export class Service {
findById(
name: string,
id: string,
query: { _embed?: string[] },
query: { _embed?: string[] | string },
): Item | undefined {
const value = this.#get(name)
if (Array.isArray(value)) {
let item = value.find((item) => item['id'] === id)
query._embed?.forEach((related) => {
ensureArray(query._embed).forEach((related) => {
if (item !== undefined) item = embed(this.#db, name, item, related)
})
return item
@@ -184,9 +188,10 @@ export class Service {
}
// Include
query._embed?.forEach((related) => {
if (items !== undefined && Array.isArray(items))
ensureArray(query._embed).forEach((related) => {
if (items !== undefined && Array.isArray(items)) {
items = items.map((item) => embed(this.#db, name, item, related))
}
})
// Return list if no query params
@@ -209,11 +214,18 @@ export class Service {
continue
}
if (
['_sort', '_start', '_end', '_limit', '_page', '_per_page'].includes(
key,
)
)
[
'_embed',
'_sort',
'_start',
'_end',
'_limit',
'_page',
'_per_page',
].includes(key)
) {
continue
}
conds[key] = [Condition.default, value]
}