Browse Source

Extract expire functionality into external module

pull/15/head
Luke Childs 8 years ago
parent
commit
f7622de1db
  1. 2
      package.json
  2. 22
      src/index.js

2
package.json

@ -27,8 +27,8 @@
"homepage": "https://github.com/lukechilds/onionoo-node-client", "homepage": "https://github.com/lukechilds/onionoo-node-client",
"dependencies": { "dependencies": {
"cache-manager": "^2.2.0", "cache-manager": "^2.2.0",
"date-fns": "^1.21.1",
"deep-assign": "^2.0.0", "deep-assign": "^2.0.0",
"expired": "^1.0.0",
"got": "^6.3.0" "got": "^6.3.0"
}, },
"devDependencies": { "devDependencies": {

22
src/index.js

@ -2,8 +2,7 @@ const got = require('got')
const cacheManager = require('cache-manager') const cacheManager = require('cache-manager')
const querystring = require('querystring') const querystring = require('querystring')
const pkg = require('../package.json') const pkg = require('../package.json')
const addSeconds = require('date-fns/add_seconds') const expired = require('expired')
const isFuture = require('date-fns/is_future')
const deepAssign = require('deep-assign') const deepAssign = require('deep-assign')
class Onionoo { class Onionoo {
@ -37,23 +36,6 @@ class Onionoo {
}, {}) }, {})
} }
// Returns expirey date from response headers
expires (headers) {
const originDate = new Date(headers.date)
// Get max age ms
let maxAge = headers['cache-control'] && headers['cache-control'].match(/max-age=(\d+)/)
maxAge = parseInt(maxAge ? maxAge[1] : 0)
// Take current age into account
if (headers.age) {
maxAge -= headers.age
}
// Calculate expirey date
return addSeconds(new Date(originDate), maxAge)
}
// Returns a function to make requests to a given endpoint // Returns a function to make requests to a given endpoint
createEndpointMethod (endpoint) { createEndpointMethod (endpoint) {
return options => { return options => {
@ -73,7 +55,7 @@ class Onionoo {
// If we have it cached // If we have it cached
if (cachedResult) { if (cachedResult) {
// Return the cached entry if it's still valid // Return the cached entry if it's still valid
if (isFuture(this.expires(cachedResult.headers))) { if (!expired(cachedResult.headers)) {
return cachedResult return cachedResult
// If it's stale, add last-modified date to headers // If it's stale, add last-modified date to headers

Loading…
Cancel
Save