var router = require('express').Router(), mongoose = require('mongoose'), Metal = mongoose.model('Metal'), Price = mongoose.model('Price'), Currency = mongoose.model('Currency'); const auth = require('../auth'), utils = require('../utils'), chalk = require('chalk'); // Preload metal objects on routes with ':metal' router.param('metal', function (req, res, next, code) { Metal.findOne({ code: code }) .then(function (metal) { if (!metal) { return res.sendStatus(404); } req.metal = metal.code; return next(); }).catch(next); }); // Preload currency objects on routes with ':currency' router.param('currency', function (req, res, next, code) { req.currency = code; Currency.findOne({ code: code }) .then(function (currency) { if (!currency) { return res.sendStatus(404); } req.currency = currency.code; return next(); }).catch(next); }); router.get('/', auth.required, function (req, res, next) { var query = {}; var limit = 20; var offset = 0; const fields = ['metal', 'currency', 'exchange', 'symbol']; if (typeof req.query.limit !== 'undefined') { limit = req.query.limit; } if (typeof req.query.offset !== 'undefined') { offset = req.query.offset; } fields.forEach(field => { if (typeof req.query[field] !== 'undefined') { query[field] = req.query[field]; } }); Metal.find({}) .limit(Number(limit)) .skip(Number(offset)) .sort({ ordering: 1 }) .exec() .then(metals => { const currency = 'EUR'; Promise.all( metals.map(metal => Price.findOne({ metal: metal.code, currency: currency })) ).then(results => { let queries$ = []; var prices = results.map((price, index) => { if (!price) { price = new Price({ metal: metals[index].code, currency: currency }); } const now = new Date().getTime(); const diff = parseInt(((now - price.timestamp) / 1000)); if (diff >= 50) { queries$.push(utils.fetchApi(price, res).then(result => { if (result.errors === undefined) { price.overwrite(result); price.save(); console.log(`${utils.getDateTimeISOString()}`, chalk.green(`${price.metal} | ${price.currency} - Sauvegarde du prix spot`), chalk.magenta(price.price)); } else { console.log(`${utils.getDateTimeISOString()}`, chalk.red(`${price.metal} | ${price.currency} - Une erreur ${result.errors.code} '${result.errors.type}' est survenue : ${result.errors.name} ${result.errors.message}`)); } return price; })); } else { console.log(`${utils.getDateTimeISOString()}`, chalk.cyan(`${price.metal} | ${price.currency} - Utilisation du prix spot`), chalk.magenta(price.price)); } return price; }); if (queries$.length) { Promise.all( queries$ ).then(() => { return res.json({ prices: prices, pricesCount: prices.length }); }).catch(next); } else { return res.json({ prices: prices, pricesCount: results[2] }); } }).catch(next); } ); }); router.get('/:metal/:currency', auth.required, function (req, res, next) { Price.findOne({ metal: req.metal, currency: req.currency }) .then(function (price) { if (!price) { price = new Price({ metal: req.metal, currency: req.currency }); } const now = new Date().getTime(); const diff = parseInt(((now - price.timestamp) / 1000)); if (diff >= 50) { utils.fetchApi(price, res).then(result => { if (result.errors === undefined) { price.overwrite(result); return price.save().then(function (data) { console.log(`${utils.getDateTimeISOString()}`, chalk.green(`${data.metal} | ${data.currency} - Enregistrement du prix spot`), chalk.magenta(data.price)); return res.json({ price: data.toJSONFor() }); }); } else { console.log(`${utils.getDateTimeISOString()}`, chalk.red(`${price.metal} | ${price.currency} - Une erreur ${result.errors.code} '${result.errors.type}' est survenue : `), chalk.red(`${result.errors.name} ${result.errors.message}`)); return res.json({ price: price }); } }); } else { console.log(`${utils.getDateTimeISOString()}`, chalk.cyan(`${price.metal} | ${price.currency} - Utilisation du prix stocké`), chalk.magenta(price.price)); return res.json({ price: price.toJSONFor() }); } }).catch(next); }); module.exports = router;