From: xangelo Date: Wed, 6 Apr 2022 17:02:32 +0000 (-0400) Subject: express wrapper improvements X-Git-Url: https://git.xangelo.ca/?p=rss-reader.git;a=commitdiff_plain;h=d9d4f30790381b8d786a1effb5ac64d8f56a6dd3 express wrapper improvements The express wrapper to allow for async/awaits style handlers now supports GET | POST | DELETE, and always properly ends the request. Views are now optional, and if they are not provided and an HTML version of the page is requested, then we send back a 204 NO CONTENT. --- diff --git a/src/server.ts b/src/server.ts index 6c94532..f140649 100644 --- a/src/server.ts +++ b/src/server.ts @@ -19,7 +19,7 @@ app.use((req, res, next) => { type WrappedApiHandler = (req: Request, res: Response) => Promise; -function apiWrapper(method: 'get' | 'post', endpoint: string, fn: WrappedApiHandler, view?: (args: any) => string) : void { +function apiWrapper(method: 'get' | 'post' | 'delete', endpoint: string, fn: WrappedApiHandler, view?: (args: any) => string) : void { app[method](endpoint, async(req, res) => { try { const output = await fn(req, res); @@ -28,15 +28,12 @@ function apiWrapper(method: 'get' | 'post', endpoint: string, fn: WrappedApiHand return; } - if(!view) { - res.send(output); - return; - } - - const viewOutput = view(output); - if(viewOutput.length) { - res.send(viewOutput); - return; + if(view) { + const viewOutput = view(output); + if(viewOutput.length) { + res.send(viewOutput); + return; + } } res.status(204); @@ -45,16 +42,22 @@ function apiWrapper(method: 'get' | 'post', endpoint: string, fn: WrappedApiHand console.error(e); res.status(500); } + finally { + res.end(); + } }); } -function apiGet(endpoint: string, fn: WrappedApiHandler, view: (arr: any) => string): void { +function apiGet(endpoint: string, fn: WrappedApiHandler, view?: (arr: any) => string): void { apiWrapper('get', endpoint, fn, view); } -function apiPost(endpoint: string, fn: WrappedApiHandler, view: (arr: any) => string): void { +function apiPost(endpoint: string, fn: WrappedApiHandler, view?: (arr: any) => string): void { apiWrapper('post', endpoint, fn, view); } +function apiDelete(endpoint: string, fn: WrappedApiHandler, view?: (arr: any) => string): void { + apiWrapper('delete', endpoint, fn, view); +} apiPost('/feeds', async (req, res): Promise => { // get info about the feed @@ -79,8 +82,6 @@ apiPost('/feeds', async (req, res): Promise => { title, url } -}, (feed: any): string => { - return ''; }); apiGet('/feeds', async (req, res): Promise => {