Skip to content

Instantly share code, notes, and snippets.

@robwalkerco
Created April 5, 2017 14:10
Show Gist options
  • Save robwalkerco/cf9d9c5ecb9e7d073458a7bf960f893e to your computer and use it in GitHub Desktop.
Save robwalkerco/cf9d9c5ecb9e7d073458a7bf960f893e to your computer and use it in GitHub Desktop.
An alternative redux-persist storage for React Native Android to get around the database item size limit - https://github.com/rt2zz/redux-persist/issues/284
/**
* @flow
*/
import RNFetchBlob from 'react-native-fetch-blob'
const DocumentDir = RNFetchBlob.fs.dirs.DocumentDir
const storagePath = `${DocumentDir}/persistStore`
const encoding = 'utf8'
const toFileName = (name: string) => name.split(':').join('-')
const fromFileName = (name: string) => name.split('-').join(':')
const pathForKey = (key: string) => `${storagePath}/${toFileName(key)}`
const AndroidFileStorage = {
setItem: (
key: string,
value: string,
callback?: ?(error: ?Error) => void,
) =>
new Promise((resolve, reject) =>
RNFetchBlob.fs.writeFile(pathForKey(key), value, encoding)
.then(() => {
if (callback) {
callback()
}
resolve()
})
.catch(error => {
if (callback) {
callback(error && error)
}
reject(error)
})
),
getItem: (
key: string,
callback?: ?(error: ?Error, result: ?string) => void
) =>
new Promise((resolve, reject) =>
RNFetchBlob.fs.readFile(pathForKey(toFileName(key)), encoding)
.then(data => {
if (callback) {
callback(null, data)
}
resolve(data)
})
.catch(error => {
if (callback) {
callback(error)
}
reject(error)
})
),
removeItem: (
key: string,
callback?: ?(error: ?Error) => void,
) =>
new Promise((resolve, reject) =>
RNFetchBlob.fs.unlink(pathForKey(toFileName(key)))
.then(() => {
if (callback) {
callback()
}
resolve()
})
.catch(error => {
if (callback) {
callback(error)
}
reject(error)
})
),
getAllKeys: (
callback?: ?(error: ?Error, keys: ?Array<string>) => void,
) =>
new Promise((resolve, reject) =>
RNFetchBlob.fs.exists(storagePath)
.then(exists =>
exists ? Promise.resolve() : RNFetchBlob.fs.mkdir(storagePath)
)
.then(() =>
RNFetchBlob.fs.ls(storagePath)
.then(files => files.map(file => fromFileName(file)))
.then(files => {
if (callback) {
callback(null, files)
}
resolve(files)
})
)
.catch(error => {
if (callback) {
callback(error)
}
reject(error)
})
),
}
export default AndroidFileStorage
@robwalkerco
Copy link
Author

This storage implementation is largely based on AsyncStorage but uses react-native-fetch-blob instead.

@frostney
Copy link

frostney commented Apr 5, 2017

Would you mind publishing this to NPM?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment