From 91993e41e14e47374d3786e3a82234012be6a865 Mon Sep 17 00:00:00 2001 From: Evan Patterson Date: Fri, 3 Aug 2018 15:24:56 -0700 Subject: [PATCH] Handle 404 errors from CouchDB in proxy server. --- api/src/main.ts | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/api/src/main.ts b/api/src/main.ts index d54ee1e..dd2829b 100644 --- a/api/src/main.ts +++ b/api/src/main.ts @@ -4,6 +4,7 @@ import * as Config from "./config"; import * as Methods from "./methods"; // Helper functions. + const sendJSON = (res: express.Response, data: object | string) => { if (typeof data === 'object') data = JSON.stringify(data); @@ -11,7 +12,17 @@ const sendJSON = (res: express.Response, data: object | string) => { res.send(data); } +const handleGetError = (res: express.Response, next: express.NextFunction, error: any) => { + if (error.statusCode == 404) { + res.status(404); + sendJSON(res, { error: 'not_found' }); + } else { + next(); + } +} + // Create and set up Express.js app. + const app = express(); app.get('/', (req, res) => res.send('Data Science Ontology API')); @@ -27,15 +38,19 @@ app.get('/annotation/_random', }); app.get('/concept/:id', - (req, res) => { + (req, res, next) => { let { id } = req.params; - Methods.getConcept(id).then(body => sendJSON(res, body)); + Methods.getConcept(id) + .then(body => sendJSON(res, body)) + .catch(error => handleGetError(res, next, error)); }); app.get('/annotation/:lang/:pkg/:id', - (req, res) => { + (req, res, next) => { let { lang, pkg, id } = req.params; - Methods.getAnnotation(lang, pkg, id).then(body => sendJSON(res, body)); + Methods.getAnnotation(lang, pkg, id) + .then(body => sendJSON(res, body)) + .catch(error => handleGetError(res, next, error)); }); app.get('/concepts', @@ -66,12 +81,15 @@ app.get('/search/annotation/:text', }); app.get('/_cache/annotation/:lang/:pkg/:id', - (req, res) => { + (req, res, next) => { let { lang, pkg, id } = req.params; const _id = `annotation/${lang}/${pkg}/${id}`; - Methods.getCache(_id).then(body => sendJSON(res, body)); + Methods.getCache(_id) + .then(body => sendJSON(res, body)) + .catch(error => handleGetError(res, next, error)); }); // Start the app! + app.listen(Config.port, () => console.log( `Data Science Ontology proxy server listening on port ${Config.port}`)); \ No newline at end of file