Skip to content

Commit

Permalink
feat(js-sdk): cache settings in Web storage for performance
Browse files Browse the repository at this point in the history
  • Loading branch information
softvar committed Aug 4, 2021
1 parent 1afeda6 commit 9fd5de2
Show file tree
Hide file tree
Showing 12 changed files with 243 additions and 53 deletions.
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).


## [1.20.0] - 2021-08-04

### Added

- Added support for JavaScript SDK to connect User Storage Service with `getSettingsFile` API so that settings could be stored and fetched before sending a network call.
- Added support for two new methods - `getSettings` and `setSettings` in User Storage Service. These will be called by SDK, if provided, when `getSettingsFile` API is invoked.

## [1.19.1] - 2021-08-02

### Changed
Expand Down
103 changes: 78 additions & 25 deletions dist/vwo-javascript-sdk.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion dist/vwo-javascript-sdk.js.map

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions dist/vwo-javascript-sdk.min.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion dist/vwo-javascript-sdk.min.js.map

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions lib/enums/LogMessageEnum.js
Original file line number Diff line number Diff line change
Expand Up @@ -125,9 +125,9 @@ module.exports = {
VARIATION_RANGE_ALLOCATION:
'({file}): Campaign:{campaignKey} having variation:{variationName} with weight:{variationWeight} got range as: ( {start} - {end} ))',
GOAL_ALREADY_TRACKED:
'({file}): "Goal:{goalIdentifier} of Campaign:{campaignKey} for User ID:{userId} has already been tracked earlier. Skipping now',
'({file}): Goal:{goalIdentifier} of Campaign:{campaignKey} for User ID:{userId} has already been tracked earlier. Skipping now',
USER_ALREADY_TRACKED:
'({file}): "User ID:{userId} for Campaign:{campaignKey} has already been tracked earlier for "{api}" API. Skipping now',
'({file}): User ID:{userId} for Campaign:{campaignKey} has already been tracked earlier for "{api}" API. Skipping now',
POLLING_SUCCESS: '({file}): Settings-file fetched successfully via polling for the accountId:{accountId}',
SETTINGS_FILE_UPDATED:
'({file}): vwo-sdk instance is updated with the latest settings-file for the accountId:{accountId}',
Expand Down
12 changes: 11 additions & 1 deletion lib/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ declare module 'vwo-node-sdk' {
*
* @returns Settings file.
*/
export function getSettingsFile(accountId: string, apiKey: string): Promise<object>;
export function getSettingsFile(accountId: string, apiKey: string, userStorageService?: VWOUserStorageConfig): Promise<object>;

/**
* Creates an instance of the VWO
Expand Down Expand Up @@ -294,6 +294,16 @@ declare module 'vwo-node-sdk' {
* @param userStorageData Variation mapping.
*/
set(userStorageData: Record<string, any>): void;

/**
* Get the stored VWO settings
*/
getSettings?(): string;
/**
* Store the VWO settings into storage(Web)
* @param settings VWO settings
*/
setSettings?(settings: string): void;
}

/**
Expand Down
2 changes: 1 addition & 1 deletion lib/services/SettingsFileManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ class SettingsFileManager {
*/
getAndUpdateSettingsFile(accountId = this._clonedSettingsFile.accountId, sdkKey = this._clonedSettingsFile.sdkKey) {
return new Promise((resolve, _reject) => {
SettingsFileUtil.get(accountId, sdkKey, { isViaWebhook: true })
SettingsFileUtil.get(accountId, sdkKey, null, { isViaWebhook: true })
.then(settings => {
this.updateSettingsFile(settings);
resolve(settings);
Expand Down
5 changes: 3 additions & 2 deletions lib/utils/SettingsFileUtil.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const UrlEnum = require('../enums/UrlEnum');
const { getRandomNumber, getCurrentTime } = require('./FunctionUtil');

module.exports = {
get: (accountId, sdkKey, config = {}) => {
get: (accountId, sdkKey, userStorageService, config = {}) => {
if (!accountId || !sdkKey) {
console.error('AccountId and sdkKey are required for fetching account settings. Aborting!');
return;
Expand Down Expand Up @@ -52,7 +52,8 @@ module.exports = {
if (typeof process.env === 'undefined') {
return require('./XhrUtil').send({
method: 'GET',
url: `${protocol}://${hostname}${path}`
url: `${protocol}://${hostname}${path}`,
userStorageService
});
} else {
const http = require('http');
Expand Down
87 changes: 69 additions & 18 deletions lib/utils/XhrUtil.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,34 +15,85 @@
*/

const { getCurrentTime } = require('./FunctionUtil');
const { isObject, isFunction } = require('./DataTypeUtil');

const XhrUtil = {
send: function({ method, url } = {}) {
_getStoredSettings: function(userStorageService) {
let isStoredData = false;
let parsedSettings;

if (userStorageService && isObject(userStorageService) && isFunction(userStorageService.getSettings)) {
try {
const settings = userStorageService.getSettings();
parsedSettings = JSON.parse(settings);

if (parsedSettings && isObject(parsedSettings) && Object.keys(parsedSettings).length > 3) {
const info = `VWO-SDK - [INFO]: ${getCurrentTime()} VWO settings found in Storage Service.`;

console.info(info);

isStoredData = true;
} else if (parsedSettings) {
const error = `VWO-SDK - [ERROR]: ${getCurrentTime()} VWO settings found in Storage Service is not valid.`;

console.error(error);
} else {
const warning = `VWO-SDK - [WARNING]: ${getCurrentTime()} VWO settings is empty in Storage Service.`;

console.warn(warning);
}
} catch (err) {
const error = `VWO-SDK - [ERROR]: ${getCurrentTime()} VWO settings found in Storage Service is not valid. ${err}`;

console.error(error);
isStoredData = false;
}
}

return {
isStoredData,
parsedSettings
};
},
send: function({ method, url, userStorageService } = {}) {
if (!url || !method) {
return;
}

return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
const { isStoredData, parsedSettings } = XhrUtil._getStoredSettings(userStorageService);

xhr.open(method, url);
xhr.send();
if (isStoredData) {
resolve(parsedSettings);
} else {
let xhr = new XMLHttpRequest();

xhr.onload = function() {
try {
resolve(JSON.parse(xhr.response));
} catch (err) {
console.error(err);
}
};
xhr.open(method, url);
xhr.send();

xhr.onerror = function() {
let error = `VWO-SDK - [ERROR]: ${getCurrentTime()} Request failed for fetching account settings. Got Status Code: ${
xhr.status
}`;
xhr.onload = function() {
try {
let parsedXhrResponse = JSON.parse(xhr.response);

console.error(error);
reject(error);
};
if (userStorageService && isObject(userStorageService) && isFunction(userStorageService.setSettings)) {
userStorageService.setSettings(xhr.response);
}

resolve(parsedXhrResponse);
} catch (err) {
console.error(err);
}
};

xhr.onerror = function() {
let error = `VWO-SDK - [ERROR]: ${getCurrentTime()} Request failed for fetching account settings. Got Status Code: ${
xhr.status
}`;

console.error(error);
reject(error);
};
}
});
}
};
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"scripts": {
"build": "yarn build:dev && yarn build:prod",
"build:dev": "webpack --mode=development",
"build:dev-watch": "webpack --mode=development --watch",
"build:dev-analyze": "webpack --mode=development --analyze=1",
"build:prod": "webpack --mode=production",
"build:patch": "webpack --mode=development --type=patch && webpack --mode=production --type=patch",
Expand Down
Loading

0 comments on commit 9fd5de2

Please sign in to comment.