Created
June 5, 2023 09:52
-
-
Save majirosstefan/153a4afd32cd5835384b2edc9ce80e11 to your computer and use it in GitHub Desktop.
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
import RNFetchBlob from 'rn-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