Skip to content

fix: add cache decorator when getting ip address #5010

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 4, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions lib/services/ip-service.ts
Original file line number Diff line number Diff line change
@@ -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<string> {
const ipAddress = await this.getIPAddressFromServiceReturningJSONWithIPProperty(this.$config.WHOAMI_URL_ENDPOINT) ||
await this.getIPAddressFromServiceReturningJSONWithIPProperty("https://api.myip.com") ||
Expand Down
20 changes: 20 additions & 0 deletions test/services/ip-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Server.IHttpClient>("httpClient");
let httpRequestCounter = 0;
httpClient.httpRequest = async (options: any, proxySettings?: IProxySettings): Promise<Server.IResponse> => {
httpRequestCounter++;
return <any>{ body: JSON.stringify({ ip }) };
};

const ipService = testInjector.resolve<IIPService>("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);
});
});
});