Skip to content

Commit

Permalink
fix: _embed param
Browse files Browse the repository at this point in the history
  • Loading branch information
typicode committed Jan 12, 2024
1 parent a4d829a commit a4dda8e
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 8 deletions.
4 changes: 4 additions & 0 deletions src/app.test.ts
Expand Up @@ -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'
Expand All @@ -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 },
Expand Down
28 changes: 20 additions & 8 deletions src/service.ts
Expand Up @@ -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[]
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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]
}

Expand Down

0 comments on commit a4dda8e

Please sign in to comment.