From c317abee78e6782ecd892642ab3fb20b77da20fb Mon Sep 17 00:00:00 2001 From: fatme Date: Tue, 3 Sep 2019 16:58:54 +0300 Subject: [PATCH 1/2] fix: add cache decorator when getting ip address --- lib/services/ip-service.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lib/services/ip-service.ts b/lib/services/ip-service.ts index d1a5d9e17d..9815c9bebd 100644 --- a/lib/services/ip-service.ts +++ b/lib/services/ip-service.ts @@ -1,9 +1,12 @@ +import { cache } from "../common/decorators"; + export class IPService implements IIPService { private static GET_IP_TIMEOUT = 1000; constructor(private $config: IConfiguration, private $httpClient: Server.IHttpClient, private $logger: ILogger) { } + @cache() public async getCurrentIPv4Address(): Promise { const ipAddress = await this.getIPAddressFromServiceReturningJSONWithIPProperty(this.$config.WHOAMI_URL_ENDPOINT) || await this.getIPAddressFromServiceReturningJSONWithIPProperty("https://api.myip.com") || From 3ace105439e90d1ff8fb65afd8e87594f6f2945b Mon Sep 17 00:00:00 2001 From: fatme Date: Wed, 4 Sep 2019 10:54:54 +0300 Subject: [PATCH 2/2] test: add unit test verifying the whoami endpoint will be called only once per process --- test/services/ip-service.ts | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/test/services/ip-service.ts b/test/services/ip-service.ts index 0d91ebe0d5..c2750f6ebf 100644 --- a/test/services/ip-service.ts +++ b/test/services/ip-service.ts @@ -135,5 +135,25 @@ describe("ipService", () => { assert.isTrue(logger.traceOutput.indexOf(errMsgForMyipCom) !== -1, `Trace output\n'${logger.traceOutput}'\ndoes not contain expected message:\n${errMsgForMyipCom}`); assert.isTrue(logger.traceOutput.indexOf(errMsgForIpifyOrg) !== -1, `Trace output\n'${logger.traceOutput}'\ndoes not contain expected message:\n${errMsgForMyipCom}`); }); + + it("is called only once per process", async () => { + const testInjector = createTestInjector(); + const httpClient = testInjector.resolve("httpClient"); + let httpRequestCounter = 0; + httpClient.httpRequest = async (options: any, proxySettings?: IProxySettings): Promise => { + httpRequestCounter++; + return { body: JSON.stringify({ ip }) }; + }; + + const ipService = testInjector.resolve("ipService"); + + const ipAddress = await ipService.getCurrentIPv4Address(); + assert.equal(httpRequestCounter, 1); + assert.equal(ipAddress, ip); + + const ipAddress2 = await ipService.getCurrentIPv4Address(); + assert.equal(httpRequestCounter, 1); + assert.equal(ipAddress2, ip); + }); }); });