From aa2e6b92611d0bead48202028ec468f8107485ff Mon Sep 17 00:00:00 2001 From: Tristan Matthias Date: Wed, 5 Dec 2018 19:12:10 +1100 Subject: [PATCH] feat(plugin-core-api): added format option in query string --- packages/core-server/package.json | 2 ++ packages/plugin-core-api/src/index.ts | 28 +++++++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/packages/core-server/package.json b/packages/core-server/package.json index 1775f91..3694736 100644 --- a/packages/core-server/package.json +++ b/packages/core-server/package.json @@ -24,6 +24,8 @@ "helmet": "^3.12.0", "http-status-codes": "^1.3.0", "ip": "^1.1.5", + "js2xmlparser": "^3.0.0", + "json-2-csv": "^2.4.0", "json-query": "^2.2.2", "pluralize": "^7.0.0", "tcp-port-used": "^1.0.1" diff --git a/packages/plugin-core-api/src/index.ts b/packages/plugin-core-api/src/index.ts index 7f26b8d..b9a7e53 100644 --- a/packages/plugin-core-api/src/index.ts +++ b/packages/plugin-core-api/src/index.ts @@ -12,6 +12,33 @@ module.exports = async (app: any, options: any) => { // ------------------------------------------------------------ Setup models const api = new Route('/api/v1'); + const contentType = new Route(); + + // Enforce all requests to be JSON by default (even errors) + // This can be overridden by the Accepts header on the request + + contentType + .position('init') + .use((req, res, next) => { + if (req.originalUrl.match(/^\/api\/v1\//)) res.contentType('json'); + if (req.query.format) { + switch (req.query.format) { + case 'json': + res.contentType('json'); + break; + case 'html': + res.contentType('html'); + break; + case 'xml': + res.contentType('xml'); + break; + case 'csv': + res.contentType('text/csv'); + } + } + + next(); + }); // If the body has a password, hash it for all routes api @@ -37,5 +64,6 @@ module.exports = async (app: any, options: any) => { next(); }); + app.useRouter(contentType); app.useRouter(api); };