Created
July 13, 2017 20:18
-
-
Save 1fabiopereira/2e052e4075f9130231e6cc11ff546e14 to your computer and use it in GitHub Desktop.
React-native cache lib
This file contains hidden or 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
/** | |
* MIT Licensed | |
* | |
* @author Fábio Pereira <[email protected]> | |
*/ | |
import {Storage} from "../../config"; | |
/* Tempo em minutos */ | |
const defaultTime = 15; | |
/* 1 minuto em milesegundos */ | |
const MINUTE = 6000; | |
/* Configuração padrão */ | |
const defaultConfig = { | |
db: Storage.Cache, | |
time: defaultTime | |
}; | |
/* Função que pega a diferença em minutos entre duas datas */ | |
const getDateDiffInMinutes = (dateA = new Date(), dateB = new Date()) => { | |
const timeA = dateA.getTime(); | |
const timeB = dateB.getTime(); | |
return (timeA - timeB) / MINUTE; | |
}; | |
class Cache { | |
/** | |
* Construtor Cache | |
* | |
* @param {Object} config Json com as configurações de cache | |
* @author Fábio Pereira <[email protected]> | |
* @constructor | |
*/ | |
constructor (config = defaultConfig) { | |
this.config = config; | |
} | |
/** | |
* Verifica se o arquivo de cache está com a data expirada | |
* | |
* @param {string} cacheName URI da rota | |
* @author Fábio Pereira <[email protected]> | |
* @return {bool} expired | |
*/ | |
async isExpired (cacheName) { | |
await this.config.db.Cache.find({where: {key: btoa(cacheName)}}). | |
then((data) => { | |
if (Object.prototype.hasOwnProperty.call(data, expires)) { | |
const now = new Date(); | |
const expires = new Date(data.expires); | |
// eslint-disable-next-line no-magic-numbers | |
return getDateDiffInMinutes(now, expires) >= 0; | |
} | |
return true; | |
}). | |
catch(() => true); | |
} | |
/** | |
* Salva o conteúdo no BD | |
* | |
* @param {string} cacheName URI da rota | |
* @param {Object} data Conteúdo a ser armazenado no cache | |
* @author Fábio Pereira <[email protected]> | |
* @return {bool} saved | |
*/ | |
save (cacheName, data) { | |
const now = new Date(); | |
const defaultTimeMs = defaultTime * MINUTE; | |
} | |
/** | |
* Retorna o conteúdo do cache | |
* | |
* @param {string} cacheName URI da rota | |
* @author Fábio Pereira <[email protected]> | |
* @return {object} data Dados da rota | |
*/ | |
async get (cacheName) { | |
await this.config.db.Cache.find({where: {key: btoa(cacheName)}}). | |
then((data) => data). | |
catch((err) => err); | |
} | |
} | |
export default Cache; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment