-
-
Save santospatrick/4dcc376e259b5b5e40cb19c5d32f0764 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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment