Skip to content

fix: remove local caching of getting company data #4997

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
Aug 30, 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
43 changes: 3 additions & 40 deletions lib/controllers/company-insights-controller.ts
Original file line number Diff line number Diff line change
@@ -1,63 +1,26 @@

import { AnalyticsEventLabelDelimiter } from "../constants";
import { cache } from "../common/decorators";
import * as path from "path";
import * as util from "util";

export class CompanyInsightsController implements ICompanyInsightsController {
private static CACHE_TIMEOUT = 30 * 24 * 60 * 60 * 1000; // 30 days in milliseconds
private get $jsonFileSettingsService(): IJsonFileSettingsService {
return this.$injector.resolve<IJsonFileSettingsService>("jsonFileSettingsService", {
jsonFileSettingsPath: path.join(this.$settingsService.getProfileDir(), "company-insights-data.json")
});
}

constructor(private $config: IConfiguration,
private $httpClient: Server.IHttpClient,
private $injector: IInjector,
private $ipService: IIPService,
private $logger: ILogger,
private $settingsService: ISettingsService) { }
private $logger: ILogger) { }

public async getCompanyData(): Promise<ICompanyData> {
let companyData: ICompanyData = null;
const { currentPublicIP, cacheKey } = await this.getIPInfo();

companyData = await this.getCompanyDataFromCache(cacheKey);

if (!companyData && currentPublicIP) {
companyData = await this.getCompanyDataFromPlaygroundInsightsEndpoint(currentPublicIP);
if (companyData && currentPublicIP) {
await this.$jsonFileSettingsService.saveSetting<ICompanyData>(cacheKey, companyData, { useCaching: true });
}
}

return companyData;
}

private async getIPInfo(): Promise<{ currentPublicIP: string, cacheKey: string }> {
let currentPublicIP: string = null;
let keyInJsonFile: string = null;

try {
currentPublicIP = await this.$ipService.getCurrentIPv4Address();
keyInJsonFile = `companyInformation_${currentPublicIP}`;
} catch (err) {
this.$logger.trace(`Unable to get current public ip address. Error is: `, err);
}

return { currentPublicIP, cacheKey: keyInJsonFile };
}

private async getCompanyDataFromCache(keyInJsonFile: string): Promise<ICompanyData> {
let companyData: ICompanyData = null;

try {
if (keyInJsonFile) {
companyData = await this.$jsonFileSettingsService.getSettingValue<ICompanyData>(keyInJsonFile, { cacheTimeout: CompanyInsightsController.CACHE_TIMEOUT });
}
} catch (err) {
this.$logger.trace(`Unable to get data from file, error is:`, err);
if (currentPublicIP) {
companyData = await this.getCompanyDataFromPlaygroundInsightsEndpoint(currentPublicIP);
}

return companyData;
Expand Down
21 changes: 21 additions & 0 deletions test/config/config-json.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { assert } from "chai";
describe("config.json", () => {
const expectedData = {
"DEBUG": false,
"TYPESCRIPT_COMPILER_OPTIONS": {},
"ANDROID_DEBUG_UI_MAC": "Google Chrome",
"USE_POD_SANDBOX": false,
"DISABLE_HOOKS": false,
"UPLOAD_PLAYGROUND_FILES_ENDPOINT": "https://play.nativescript.org/api/files",
"SHORTEN_URL_ENDPOINT": "https://play.nativescript.org/api/shortenurl?longUrl=%s",
"INSIGHTS_URL_ENDPOINT": "https://play-server.nativescript.org/api/insights?ipAddress=%s",
"WHOAMI_URL_ENDPOINT": "https://play.nativescript.org/api/whoami",
"PREVIEW_APP_ENVIRONMENT": "live",
"GA_TRACKING_ID": "UA-111455-51"
};

it("validates content is correct", () => {
const data = require("../../config/config.json");
assert.deepEqual(data, expectedData, "Data in config.json is not correct. Is this expected?");
});
});
79 changes: 1 addition & 78 deletions test/controllers/company-insights-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@ import { CompanyInsightsController } from "../../lib/controllers/company-insight
describe("companyInsightsController", () => {
const insightsUrlEndpoint = "/api/insights?ipAddress=%s";
const currentIp = "8.8.8.8";
const profileDir = "profileDir";
const cacheTimeout = 30 * 24 * 60 * 60 * 1000; // 2 days in milliseconds
const defaultCompanyData = {
company: {
name: "Progress",
Expand All @@ -29,26 +27,6 @@ describe("companyInsightsController", () => {
employeeCount: "500"
};

const defaultExpectedDataPassedToGetSetting: any[] = [{ settingName: `companyInformation_${currentIp}`, cacheOpts: { cacheTimeout } }];
const defaultExpectedDataPassedToSaveSetting: any[] = [
{
cacheOpts: {
useCaching: true
},
key: "companyInformation_8.8.8.8",
value: {
country: "Bulgaria",
employeeCount: "500",
industries: "Software__Software 2",
name: "Progress",
revenue: "123131"
}
}
];

let dataPassedToGetSettingValue: { settingName: string, cacheOpts?: ICacheTimeoutOpts }[] = [];
let dataPassedToSaveSettingValue: { key: string, value: any, cacheOpts?: IUseCacheOpts }[] = [];
let getSettingValueResult: IDictionary<any> = null;
let httpRequestCounter = 0;
let httpRequestResult: any = null;
let testInjector: IInjector = null;
Expand All @@ -68,43 +46,24 @@ describe("companyInsightsController", () => {
});

injector.register("logger", LoggerStub);
injector.register("injector", injector);
injector.register("ipService", {
getCurrentIPv4Address: async (): Promise<string> => currentIp
});

injector.register("settingsService", {
getProfileDir: (): string => profileDir
});

injector.register("jsonFileSettingsService", {
getSettingValue: async (settingName: string, cacheOpts?: ICacheTimeoutOpts): Promise<any> => {
dataPassedToGetSettingValue.push({ settingName, cacheOpts });
return getSettingValueResult;
},

saveSetting: async (key: string, value: any, cacheOpts?: IUseCacheOpts): Promise<void> => {
dataPassedToSaveSettingValue.push({ key, value, cacheOpts });
}
});

injector.register("companyInsightsController", CompanyInsightsController);

return injector;
};

beforeEach(() => {
dataPassedToGetSettingValue = [];
dataPassedToSaveSettingValue = [];
getSettingValueResult = null;
httpRequestCounter = 0;
httpRequestResult = defaultCompanyData;
testInjector = createTestInjector();
companyInsightsController = testInjector.resolve<ICompanyInsightsController>("companyInsightsController");
});

describe("getCompanyData", () => {
describe("returns null when data does not exist in the cache and", () => {
describe("returns null when", () => {
it("the http client fails to get data", async () => {
const httpClient = testInjector.resolve<Server.IHttpClient>("httpClient");
const errMsg = "custom error";
Expand Down Expand Up @@ -146,31 +105,13 @@ describe("companyInsightsController", () => {
const companyData = await companyInsightsController.getCompanyData();
assert.deepEqual(companyData, null);
assert.equal(httpRequestCounter, 0, "We should not have any http request");
assert.deepEqual(dataPassedToGetSettingValue, [], "When we are unable to get IP, we should not try to get value from the cache.");
assert.deepEqual(dataPassedToSaveSettingValue, [], "When we are unable to get IP, we should not persist anything.");
});
});

describe("returns correct data when", () => {
it("data for current ip exist in the cache", async () => {
httpRequestResult = null;

getSettingValueResult = defaultExpectedCompanyData; // data in the file should be in the already parsed format
const companyData = await companyInsightsController.getCompanyData();
assert.deepEqual(companyData, defaultExpectedCompanyData);

assert.equal(httpRequestCounter, 0, "In case we have data for the company in our cache, we should not make any http requests");
assert.deepEqual(dataPassedToGetSettingValue, defaultExpectedDataPassedToGetSetting);
assert.deepEqual(dataPassedToSaveSettingValue, []);
});

describe("data for current ip does not exist in the cache and", () => {

it("response contains company property", async () => {
const companyData = await companyInsightsController.getCompanyData();
assert.deepEqual(companyData, defaultExpectedCompanyData);
assert.deepEqual(dataPassedToGetSettingValue, defaultExpectedDataPassedToGetSetting);
assert.deepEqual(dataPassedToSaveSettingValue, defaultExpectedDataPassedToSaveSetting);
});

it("response contains company property and industries in it are not populated", async () => {
Expand All @@ -191,26 +132,8 @@ describe("companyInsightsController", () => {
industries: null,
employeeCount: "500"
});

assert.deepEqual(dataPassedToGetSettingValue, defaultExpectedDataPassedToGetSetting);
assert.deepEqual(dataPassedToSaveSettingValue, [
{
cacheOpts: {
useCaching: true
},
key: "companyInformation_8.8.8.8",
value: {
country: "Bulgaria",
employeeCount: "500",
industries: null,
name: "Progress",
revenue: "123131"
}
}
]);
});

});
});

it("is called only once per process", async () => {
Expand Down