Skip to content

Instantly share code, notes, and snippets.

@tleunen
Last active May 30, 2018 02:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tleunen/2da8bb7efb8cff5319ca195d49ed2f21 to your computer and use it in GitHub Desktop.
Save tleunen/2da8bb7efb8cff5319ca195d49ed2f21 to your computer and use it in GitHub Desktop.
webtask-openexchangerate
const request = require('request');
const OPEN_EXCHANGE_API_URL = 'https://openexchangerates.org/api';
const OE_LATEST = `${OPEN_EXCHANGE_API_URL}/latest.json`;
module.exports = function(ctx, done) {
const APP_ID = ctx.data.APP_ID;
const url = `${OE_LATEST}?app_id=${APP_ID}`;
// Get the data from the storage to prevent unnecessary requests
ctx.storage.get((err, data) => {
if (err) {
return done(err);
}
const now = Date.now();
const dataTime = (data || {}).time || 0;
// If the data is recent enough (less than 1 hour)
if (now - dataTime <= 1 * 60 * 60 * 1000) {
return done(null, data.body);
}
// otherwise we fetch the remote api
request.get(url, (geterr, resp) => {
if (geterr) {
return done(geterr);
}
const body = JSON.parse(resp.body);
const dataBody = {
timestamp: body.timestamp,
base: body.base,
rates: body.rates
};
ctx.storage.set(
{
time: now,
body: dataBody
},
error => {
if (error) {
return done(error);
}
return done(null, dataBody);
}
);
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment