diff --git a/src/app.test.ts b/src/app.test.ts index bc19085f..cb0f6930 100644 --- a/src/app.test.ts +++ b/src/app.test.ts @@ -55,6 +55,7 @@ await test('createApp', async (t) => { // URLs const POSTS = '/posts' const POSTS_WITH_COMMENTS = '/posts?_embed=comments' + const POSTS_NESTED_WITH_COMMENTS = '/posts/1/comments' const POST_1 = '/posts/1' const POST_NOT_FOUND = '/posts/-1' const POST_WITH_COMMENTS = '/posts/1?_embed=comments' @@ -76,6 +77,7 @@ await test('createApp', async (t) => { // API { method: 'GET', url: POSTS, statusCode: 200 }, { method: 'GET', url: POSTS_WITH_COMMENTS, statusCode: 200 }, + { method: 'GET', url: POSTS_NESTED_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 }, diff --git a/src/app.ts b/src/app.ts index de3383e5..7f9dfa58 100644 --- a/src/app.ts +++ b/src/app.ts @@ -8,7 +8,7 @@ import { Low } from 'lowdb' import { json } from 'milliparsec' import sirv from 'sirv' -import { Data, isItem, Service } from './service.js' +import { Data, getNestedName, isItem, Service } from './service.js' const __dirname = dirname(fileURLToPath(import.meta.url)) const isProduction = process.env['NODE_ENV'] === 'production' @@ -68,6 +68,13 @@ export function createApp(db: Low, options: AppOptions = {}) { next() }) + app.get('/:name/:id/:nested_name', (req, res, next) => { + const { name = '', id = '', nested_name = '' } = req.params + + res.locals['data'] = service.find(nested_name, { ...req.query, [getNestedName(name)]: id}) + next() + }) + app.post('/:name', async (req, res, next) => { const { name = '' } = req.params if (isItem(req.body)) { diff --git a/src/service.ts b/src/service.ts index c6a711cc..518e8629 100644 --- a/src/service.ts +++ b/src/service.ts @@ -13,6 +13,10 @@ export function isItem(obj: unknown): obj is Item { return typeof obj === 'object' && obj !== null } +export function getNestedName(name: string): string { + return name[name.length-1] === 's' ? `${name.substring(0, name.length-1)}Id`: `${name}Id`; +} + export function isData(obj: unknown): obj is Record { if (typeof obj !== 'object' || obj === null) { return false