Skip to content

Revert "refactor: Update datafile-manager to use Async Storage implementation from utils (#508)" #525

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 5 commits into from
Jul 28, 2020
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
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import HttpPollingDatafileManager from '../src/httpPollingDatafileManager';
import { Headers, AbortableRequest, Response } from '../src/http';
import { DatafileManagerConfig } from '../src/datafileManager';
import { advanceTimersByTime, getTimerCount } from './testUtils';
import { PersistentKeyValueCache } from '@optimizely/js-sdk-utils';
import PersistentKeyValueCache from '../src/persistentKeyValueCache';

jest.mock('../src/backoffController', () => {
return jest.fn().mockImplementation(() => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/**
* Copyright 2020, Optimizely
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import ReactNativeAsyncStorageCache from '../src/reactNativeAsyncStorageCache';

describe('reactNativeAsyncStorageCache', () => {
let cacheInstance: ReactNativeAsyncStorageCache;

beforeEach(() => {
cacheInstance = new ReactNativeAsyncStorageCache();
});

describe('get', function() {
it('should return correct object when item is found in cache', function() {
return cacheInstance.get('keyThatExists').then(v => expect(v).toEqual({ name: 'Awesome Object' }));
});

it('should return null if item is not found in cache', function() {
return cacheInstance.get('keyThatDoesNotExist').then(v => expect(v).toBeNull());
});

it('should reject promise error if string has an incorrect JSON format', function() {
return cacheInstance
.get('keyWithInvalidJsonObject')
.catch(() => 'exception caught')
.then(v => {
expect(v).toEqual('exception caught');
});
});
});

describe('set', function() {
it('should resolve promise if item was successfully set in the cache', function() {
const testObj = { name: 'Awesome Object' };
return cacheInstance.set('testKey', testObj);
});

it('should reject promise if item was not set in the cache because of json stringifying error', function() {
const testObj: any = { name: 'Awesome Object' };
testObj.myOwnReference = testObj;
return cacheInstance
.set('testKey', testObj)
.catch(() => 'exception caught')
.then(v => expect(v).toEqual('exception caught'));
});
});

describe('contains', function() {
it('should return true if object with key exists', function() {
return cacheInstance.contains('keyThatExists').then(v => expect(v).toBeTruthy());
});

it('should return false if object with key does not exist', function() {
return cacheInstance.contains('keyThatDoesNotExist').then(v => expect(v).toBeFalsy());
});
});
});
6 changes: 3 additions & 3 deletions packages/datafile-manager/package-lock.json

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

3 changes: 2 additions & 1 deletion packages/datafile-manager/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
},
"main": "lib/index.node.js",
"browser": "lib/index.browser.js",
"react-native": "lib/index.react_native.js",
"types": "lib/index.d.ts",
"directories": {
"lib": "lib",
Expand Down Expand Up @@ -48,7 +49,7 @@
},
"dependencies": {
"@optimizely/js-sdk-logging": "^0.1.0",
"@optimizely/js-sdk-utils": "^0.3.2",
"@optimizely/js-sdk-utils": "^0.4.0",
"decompress-response": "^4.2.1"
},
"peerDependencies": {
Expand Down
2 changes: 1 addition & 1 deletion packages/datafile-manager/src/datafileManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { PersistentKeyValueCache } from '@optimizely/js-sdk-utils';
import PersistentKeyValueCache from './persistentKeyValueCache';

export interface DatafileUpdate {
datafile: object;
Expand Down
3 changes: 2 additions & 1 deletion packages/datafile-manager/src/httpPollingDatafileManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,13 @@
*/

import { getLogger } from '@optimizely/js-sdk-logging';
import { sprintf, PersistentKeyValueCache } from '@optimizely/js-sdk-utils';
import { sprintf } from '@optimizely/js-sdk-utils';
import { DatafileManager, DatafileManagerConfig, DatafileUpdate } from './datafileManager';
import EventEmitter, { Disposer } from './eventEmitter';
import { AbortableRequest, Response, Headers } from './http';
import { DEFAULT_UPDATE_INTERVAL, MIN_UPDATE_INTERVAL, DEFAULT_URL_TEMPLATE } from './config';
import BackoffController from './backoffController';
import PersistentKeyValueCache from './persistentKeyValueCache';

const logger = getLogger('DatafileManager');

Expand Down
60 changes: 60 additions & 0 deletions packages/datafile-manager/src/persistentKeyValueCache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/**
* Copyright 2020, Optimizely
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**
* An Interface to implement a persistent key value cache which supports strings as keys
* and JSON Object as value.
*/
export default interface PersistentKeyValueCache {
/**
* Returns value stored against a key or null if not found.
* @param key
* @returns
* Resolves promise with
* 1. Object if value found was stored as a JSON Object.
* 2. null if the key does not exist in the cache.
* Rejects the promise in case of an error
*/
get(key: string): Promise<any | null>;

/**
* Stores Object in the persistent cache against a key
* @param key
* @param val
* @returns
* Resolves promise without a value if successful
* Rejects the promise in case of an error
*/
set(key: string, val: any): Promise<void>;

/**
* Checks if a key exists in the cache
* @param key
* Resolves promise with
* 1. true if the key exists
* 2. false if the key does not exist
* Rejects the promise in case of an error
*/
contains(key: string): Promise<boolean>;

/**
* Removes the key value pair from cache.
* @param key
* Resolves promise without a value if successful
* Rejects the promise in case of an error
*/
remove(key: string): Promise<void>;
}
55 changes: 55 additions & 0 deletions packages/datafile-manager/src/reactNativeAsyncStorageCache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/**
* Copyright 2020, Optimizely
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { getLogger } from '@optimizely/js-sdk-logging';
import AsyncStorage from '@react-native-community/async-storage';

import PersistentKeyValueCache from './persistentKeyValueCache';

const logger = getLogger('DatafileManager');

export default class ReactNativeAsyncStorageCache implements PersistentKeyValueCache {
get(key: string): Promise<any | null> {
return AsyncStorage.getItem(key).then((val: string | null) => {
if (!val) {
return null;
}
try {
return JSON.parse(val);
} catch (ex) {
logger.error('Error Parsing Object from cache - %s', ex);
throw ex;
}
});
}

set(key: string, val: any): Promise<void> {
try {
return AsyncStorage.setItem(key, JSON.stringify(val));
} catch (ex) {
logger.error('Error stringifying Object to Json - %s', ex);
return Promise.reject(ex);
}
}

contains(key: string): Promise<boolean> {
return AsyncStorage.getItem(key).then((val: string | null) => val !== null);
}

remove(key: string): Promise<void> {
return AsyncStorage.removeItem(key);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { makeGetRequest } from './browserRequest';
import HttpPollingDatafileManager from './httpPollingDatafileManager';
import { Headers, AbortableRequest } from './http';
import { DatafileManagerConfig } from './datafileManager';
import { ReactNativeAsyncStorageCache } from '@optimizely/js-sdk-utils';
import ReactNativeAsyncStorageCache from './reactNativeAsyncStorageCache';

export default class ReactNativeDatafileManager extends HttpPollingDatafileManager {
protected makeGetRequest(reqUrl: string, headers: Headers): AbortableRequest {
Expand Down