Skip to content

feat: Key Value cache implementation for React Native #426

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 10 commits into from
Mar 20, 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
5 changes: 3 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -82,10 +82,11 @@ jobs:
- &packagetest
stage: 'Test sub packages'
node_js: '12'
before_install: cd packages/datafile-manager
before_install: cd packages/utils
- <<: *packagetest
before_install: cd packages/event-processor
- <<: *packagetest
before_install: cd packages/logging
- <<: *packagetest
before_install: cd packages/utils
before_script: npm install "@react-native-community/async-storage"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this necessary? The tests should not actually call into AsyncStorage - it should be mocked.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes but typescript compiles first and that needs this dependency. It eventually uses mock

before_install: cd packages/datafile-manager
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/**
* 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.
*/

export default class AsyncStorage {
static getItem(key: string, callback?: (error?: Error, result?: string) => void): Promise<string | null> {
return new Promise((resolve, reject) => {
switch (key) {
case 'keyThatExists':
resolve('{ "name": "Awesome Object" }')
break
case 'keyThatDoesNotExist':
resolve(null)
break
case 'keyWithInvalidJsonObject':
resolve('bad json }')
break
}
})
}

static setItem(key: string, value: string, callback?: (error?: Error) => void): Promise<void> {
return Promise.resolve()
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/**
* 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())
})
})
})
3 changes: 3 additions & 0 deletions packages/datafile-manager/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@
"@optimizely/js-sdk-logging": "^0.1.0",
"@optimizely/js-sdk-utils": "^0.1.0"
},
"peerDependencies": {
"@react-native-community/async-storage": "^1.2.0"
},
"scripts": {
"test": "jest",
"tsc": "rm -rf lib && tsc",
Expand Down
61 changes: 61 additions & 0 deletions packages/datafile-manager/src/persistentKeyValueCache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/**
* 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 {

/**
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For all methods in this interface, the docs need more detail about the returned promise, what value it is fulfilled with, and what causes the promise to reject.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just added more details to each method.

* 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>
}
56 changes: 56 additions & 0 deletions packages/datafile-manager/src/reactNativeAsyncStorageCache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/**
* 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)
}
}