fitssey-api
Advanced tools
Comparing version 1.0.3 to 1.1.0
54
index.js
@@ -14,3 +14,4 @@ const axios = require('axios'); | ||
cache = true, | ||
cacheTTL: stdTTL = 1800, | ||
cacheTTF: stdTTF = (60 * 60 * 12), | ||
cacheTTL: stdTTL = (60 * 60 * 24), | ||
cacheChecKPeriod: checkperiod = 120, | ||
@@ -24,2 +25,3 @@ }) { | ||
source: source !== '' ? source : uuid, | ||
cacheTTF: stdTTF, | ||
} | ||
@@ -46,3 +48,3 @@ | ||
async request( method = '', { | ||
async formatRequest( method = '', { | ||
endpoint = '', | ||
@@ -66,22 +68,32 @@ data = false, | ||
getFromCache( uid, requestParams ) { | ||
async getFromCache( uid, requestParams ) { | ||
if ( ! this.cache ) return axios(requestParams) | ||
return new Promise(( resolve, reject ) => { | ||
this.cache.get( uid, ( err, value ) => { | ||
const now = +new Date(); | ||
const value = await this.cache.get( uid ); | ||
if( ! err && value ) { | ||
const parsedData = JSON.parse( value ) | ||
return resolve( parsedData ) | ||
} | ||
if ( value ) { | ||
const parsedData = await JSON.parse( value ) | ||
return axios(requestParams).then( data => { | ||
this.setInCache ( uid, data ); | ||
return resolve(data ) | ||
} ) | ||
}) | ||
const { _ttf, ...data } = parsedData | ||
}) | ||
if ( _ttf && _ttf < now ) this.makeRequest( uid, requestParams, now) | ||
return data | ||
} | ||
const data = await this.makeRequest(uid, requestParams, now); | ||
return data | ||
} | ||
async makeRequest(uid, params, now) { | ||
const data = await axios(params); | ||
this.setInCache( uid, { | ||
_ttf: now + (this.config.cacheTTF * 1000), | ||
...data, | ||
} ); | ||
return data | ||
} | ||
setInCache( uid, data ) { | ||
@@ -95,3 +107,3 @@ if ( ! data ) return | ||
get( endpoint = '', data = false ) { | ||
return this.request( 'get', { | ||
return this.formatRequest( 'get', { | ||
endpoint, | ||
@@ -103,3 +115,3 @@ data, | ||
post( endpoint = '', data = false ) { | ||
return this.request( 'post', { | ||
return this.formatRequest( 'post', { | ||
endpoint, | ||
@@ -111,3 +123,3 @@ data, | ||
put( endpoint = '', data = false ) { | ||
return this.request( 'put', { | ||
return this.formatRequest( 'put', { | ||
endpoint, | ||
@@ -119,3 +131,3 @@ data, | ||
patch( endpoint = '', data = false ) { | ||
return this.request( 'patch', { | ||
return this.formatRequest( 'patch', { | ||
endpoint, | ||
@@ -127,3 +139,3 @@ data, | ||
delete( endpoint = '', data = false ) { | ||
return this.request( 'delete', { | ||
return this.formatRequest( 'delete', { | ||
endpoint, | ||
@@ -133,5 +145,5 @@ data, | ||
} | ||
} | ||
exports = module.exports = FitsseyApi |
{ | ||
"name": "fitssey-api", | ||
"version": "1.0.3", | ||
"version": "1.1.0", | ||
"description": "Fitssey API connection", | ||
@@ -10,3 +10,4 @@ "homepage": "https://github.com/MaartenBruggink/fittsey-api", | ||
"fitssey", | ||
"api" | ||
"api", | ||
"rest" | ||
], | ||
@@ -13,0 +14,0 @@ "repository": { |
4461
108