Browse Source

Refactor into class

xo
Luke Childs 8 years ago
parent
commit
183f5f177b
  1. 49
      src/index.js

49
src/index.js

@ -3,38 +3,53 @@ const NodeCache = require('node-cache');
const querystring = require('querystring');
const pkg = require('../package.json');
const cache = new NodeCache();
class Onionoo {
const baseUrl = 'https://onionoo.torproject.org';
const endpoints = [
// Constructor returns a new object so instance properties are private
constructor(options = {}) {
// Set default options
this.options = Object.assign({}, {
cache: new NodeCache(),
baseUrl: 'https://onionoo.torproject.org',
endpoints: [
'summary',
'details',
'bandwidth',
'weights',
'clients',
'uptime'
];
]
}, options);
// Return object containing endpoint methods
return this.options.endpoints.reduce((onionoo, endpoint) => {
onionoo[endpoint] = this.createEndpointMethod(endpoint);
return onionoo;
}, {});
}
// Returns cache max age from response headers
function checkResponseMaxAge(response) {
// Returns cache max age from response headers
checkResponseMaxAge(response) {
const cacheControl = response.headers['cache-control'];
const maxAgeRegex = /max-age=(\d+)/;
const maxAge = cacheControl && cacheControl.match(maxAgeRegex);
return maxAge && maxAge[1];
}
}
// Returns a function to make requests to a given endpoint
function createEndpointMethod(endpoint) {
// Returns a function to make requests to a given endpoint
createEndpointMethod(endpoint) {
return args => new Promise((resolve, reject) => {
// Build query string (don't encode ':' for search filters)
const qs = querystring.encode(args).replace(/%3A/g, ':');
// Build url
const url = `${baseUrl}/${endpoint}?${qs}`;
const url = `${this.options.baseUrl}/${endpoint}?${qs}`;
// Check for url in cache
const cachedResult = cache.get(url);
const cachedResult = this.options.cache.get(url);
if(cachedResult) {
resolve(cachedResult);
} else {
@ -48,9 +63,9 @@ function createEndpointMethod(endpoint) {
.then(response => {
// Cache response
const ttl = checkResponseMaxAge(response);
const ttl = this.checkResponseMaxAge(response);
if(ttl) {
cache.set(url, response.body, ttl);
this.options.cache.set(url, response.body, ttl);
}
// Resolve response
@ -58,11 +73,7 @@ function createEndpointMethod(endpoint) {
}));
}
});
}
}
// Return object containing endpoint methods
module.exports = endpoints.reduce((onionoo, endpoint) => {
onionoo[endpoint] = createEndpointMethod(endpoint);
return onionoo;
}, {});
module.exports = Onionoo;

Loading…
Cancel
Save