From 9c8f7f06c14cd15a0fac85762a28f15e24ff85bd Mon Sep 17 00:00:00 2001 From: Akalanka Date: Thu, 8 Feb 2024 21:42:29 +0530 Subject: [PATCH] Patch(service-connector): updated request interceptor handling --- packages/service-connector/src/index.js | 5 ++- packages/service-connector/test/index.test.js | 33 +++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/packages/service-connector/src/index.js b/packages/service-connector/src/index.js index 0345605..c19d3f4 100644 --- a/packages/service-connector/src/index.js +++ b/packages/service-connector/src/index.js @@ -18,9 +18,12 @@ const serviceConnector = ({ service, headerIntercepts, loggable, logs = true, .. ); config.headers["x-correlation-id"] = context.get("correlationId"); if (headerIntercepts) { + let intercepts = headerIntercepts(config); + if (intercepts instanceof Promise) + intercepts = await intercepts.catch((e) => logger.error("Failed to intercept headers", e)); config.headers = { ...config.headers, - ...(await headerIntercepts(config)) + ...intercepts }; } return config; diff --git a/packages/service-connector/test/index.test.js b/packages/service-connector/test/index.test.js index 775634b..498dede 100644 --- a/packages/service-connector/test/index.test.js +++ b/packages/service-connector/test/index.test.js @@ -66,6 +66,39 @@ describe("service-connector", () => { loggable ); }); + test("successful request with header interceptor", async () => { + const interceptedConnector = serviceConnector({ + baseURL: "https://google.com", + headerIntercepts: () => ({ + "x-api-key": "123456" + }) + }); + const response = await interceptedConnector.get("/"); + expect(response.status).toEqual(200); + }); + test("successful request with async header interceptor", async () => { + const asyncInterceptedConnector = serviceConnector({ + baseURL: "https://google.com", + headerIntercepts: async () => { + await new Promise((resolve) => setTimeout(resolve, 50)); + return; + } + }); + const response = await asyncInterceptedConnector.get("/"); + expect(response.status).toEqual(200); + }); + test("successful request ignoring error in async header interceptor", async () => { + const asyncInterceptedConnector = serviceConnector({ + baseURL: "https://google.com", + headerIntercepts: async () => { + await new Promise((_, reject) => setTimeout(reject, 50)); + return; + } + }); + const response = await asyncInterceptedConnector.get("/"); + expect(response.status).toEqual(200); + expect(mockLogger.error).toBeCalledWith(`Failed to intercept headers`, undefined); + }); }); describe("service-connector resolver", () => {