From a4dda8ec64dcf0c3572db190d03caab191a3f5cc Mon Sep 17 00:00:00 2001 From: typicode Date: Fri, 12 Jan 2024 01:09:16 +0100 Subject: [PATCH] fix: _embed param --- src/app.test.ts | 4 ++++ src/service.ts | 28 ++++++++++++++++++++-------- 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/src/app.test.ts b/src/app.test.ts index 0cb798957..a40fab6c3 100644 --- a/src/app.test.ts +++ b/src/app.test.ts @@ -54,8 +54,10 @@ await new Promise((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 }, diff --git a/src/service.ts b/src/service.ts index 2e0d597ce..bcf4c1184 100644 --- a/src/service.ts +++ b/src/service.ts @@ -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, 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] }