Last active
December 13, 2018 13:14
-
-
Save quarrant/338ff0a63fc30085be45fde488cda232 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 { AsyncStorage } from 'react-native'; | |
import _ from 'lodash'; | |
loadFromCache(model, limit = 0) { | |
return new Promise((resolve, reject) => { | |
_getModelFromAsyncStorage(model) | |
.then(results => { | |
if (!results) resolve([]); | |
if (_.isArray(results) && limit > 0 && results.length > limit) { | |
results = results.slice(Math.max(results.length - limit, 1)); | |
}; | |
resolve(results); | |
}); | |
}); | |
}; | |
insertIntoCache(model, record, { update = false, primaryKey = 'id' }) { | |
return new Promise((resolve, reject) => { | |
_getModelFromAsyncStorage(model) | |
.then((data = []) => { | |
try { | |
const source = update | |
? _.unionBy(record, data, primaryKey) | |
: _.isArray(record) | |
? record | |
: [record]; | |
this._setModelToAsyncStorage(model, source); | |
resolve(source); | |
} catch(e) { | |
reject(e) | |
}; | |
}); | |
}); | |
} | |
clearCache() { | |
return new Promise((resolve, reject) => { | |
AsyncStorage.getAllKeys((error, keys) => { | |
keys.map(k => AsyncStorage.removeItem(k)); | |
resolve(0); | |
}); | |
}) | |
} | |
_setModelToAsyncStorage(modelKey, values) { | |
return new Promise((resolve, reject) => { | |
AsyncStorage.setItem(modelKey, JSON.stringify(values), (error) => { | |
if (error) reject(error); | |
resolve(0); | |
}); | |
}); | |
} | |
_getModelFromAsyncStorage(modelKey) { | |
return new Promise((resolve, reject) => { | |
AsyncStorage.getItem(modelKey, (error, result) => { | |
try { | |
if (error) reject(error); | |
resolve(JSON.parse(result)) | |
} catch (e) { | |
reject(e); | |
}; | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Загрузка
this.loadFromCache('todos').then(todos => { ... })