From 5c27f3c57ea4a57ff68e0e2a60b6ec4efda141e7 Mon Sep 17 00:00:00 2001 From: Shreyas Adiyodi Date: Fri, 5 Mar 2021 17:12:48 +0530 Subject: [PATCH] feat: introduce new options for proxy --- plugin/proxy/index.ts | 40 ++++++++++++++++++++++++++++++++++------ plugin/proxy/utils.ts | 3 ++- 2 files changed, 36 insertions(+), 7 deletions(-) diff --git a/plugin/proxy/index.ts b/plugin/proxy/index.ts index b5bb1c2a8..993bf2495 100644 --- a/plugin/proxy/index.ts +++ b/plugin/proxy/index.ts @@ -12,6 +12,31 @@ const httpRequestClient = async (method: string, uri: string, options: any) => { return Wreck.request(method, uri, proxyOptions); }; +const onResponse = (route: any) => async ( + err: any, + res: any, + request: Hapi.Request, + h: Hapi.ResponseToolkit +) => { + const payload = await Wreck.read(res, { + json: 'force', + gunzip: true + }); + + // only return the following key from the response + const responseKeyToReturn = R.pathOr( + '', + ['options', 'app', 'proxy', 'responseKeyToReturn'], + route + ); + if (!R.hasPath(responseKeyToReturn.split('.'), payload)) { + return h.response(payload); + } + + const payloadToReturn = R.pathOr({}, responseKeyToReturn.split('.'), payload); + return h.response(payloadToReturn); +}; + export const plugin = { name: 'proxies', dependencies: [], @@ -26,12 +51,15 @@ export const plugin = { const routes = generateRoutes(routesContent); const ROUTES: any[] = routes; - const ROUTES_WITH_PROXY_DATA = ROUTES.map( - R.assocPath( - ['handler', 'proxy', 'httpClient', 'request'], - httpRequestClient - ) - ); + const ROUTES_WITH_PROXY_DATA: any[] = ROUTES.map((route) => { + return R.pipe( + R.assocPath( + ['handler', 'proxy', 'httpClient', 'request'], + httpRequestClient + ), + R.assocPath(['handler', 'proxy', 'onResponse'], onResponse(route)) + )(route); + }); server.route(ROUTES_WITH_PROXY_DATA); } diff --git a/plugin/proxy/utils.ts b/plugin/proxy/utils.ts index 20e1cd4ca..70c5d7606 100644 --- a/plugin/proxy/utils.ts +++ b/plugin/proxy/utils.ts @@ -63,7 +63,8 @@ export const generateRoutes = (contents: Array = []) => { iam: { permissions: route?.permissions || [], hooks: route?.hooks || [] - } + }, + proxy: route?.proxy?.extraOptions } } };