Browse Source

Refactor expire function to return expirey date rather than time in ms

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

1
package.json

@ -27,6 +27,7 @@
"homepage": "https://github.com/lukechilds/onionoo-node-client",
"dependencies": {
"cache-manager": "^2.2.0",
"date-fns": "^1.21.1",
"got": "^6.3.0"
},
"devDependencies": {

22
src/index.js

@ -2,6 +2,7 @@ const got = require('got')
const cacheManager = require('cache-manager')
const querystring = require('querystring')
const pkg = require('../package.json')
const addSeconds = require('date-fns/add_seconds')
class Onionoo {
@ -34,21 +35,16 @@ class Onionoo {
}, {})
}
// Returns cache max age from response headers
calculateResponseMaxAge (headers) {
// Get max age ms
const cacheControl = headers['cache-control']
const maxAgeRegex = /max-age=(\d+)/
let maxAge = cacheControl && cacheControl.match(maxAgeRegex)
maxAge = maxAge ? maxAge[1] : 0
// Returns expirey date from response headers
expires (headers) {
const originDate = new Date(headers.date)
// Take current age into account
if (headers.age) {
maxAge -= headers.age
}
// Get max age ms
let maxAge = headers['cache-control'] && headers['cache-control'].match(/max-age=(\d+)/)
maxAge = parseInt(maxAge ? maxAge[1] : 0)
// Don't return negative values
return Math.max(0, maxAge)
// Calculate expirey date
return addSeconds(new Date(originDate), maxAge)
}
// Returns a function to make requests to a given endpoint

Loading…
Cancel
Save