<commit_before>// This module provides middleware that loads currency conversion information into
// res.locals. It fetches this information from the db. The db should be refreshed everyday
// with this information so if the data is old, this middleware will make a request
// for fresh information, save it to the db, and then populate it in res.locals

import { wrap as coroutine } from 'co';
import request from 'request-promise';
import moment from 'moment';

import { required, print } from '../custom-utils';
import { getCurrentExchangeRates } from '../data';
import { insert as insertInDb } from '../db/service';

export default ({
    exchangeRatesCollection = required('exchangeRatesCollection'),
    logger = required('logger', 'You must pass in a logging instance for this api to use')
}) => coroutine(function* (req, res, next) {
    const {
        exchangeRates: {
            reqUrl: exchangeRatesUrl
        } = {}
    } = res.locals.config;

    if (!exchangeRatesUrl) {
        throw new Error('Missing exchange rates url from config');
    }

    let rates;

    // First, see if there are fresh rates in the db
    try {
        rates = yield getCurrentExchangeRates({ exchangeRatesCollection });
    } catch (e) {
        logger.error(e.err, e.msg);
        res.locals.exchangeRates = null;

        return next();
    }

    if (!rates) {
        // We need to fetch current rates and save them to the db
        let ratesResponse;

        try {
            ratesResponse = yield request({
                uri: exchangeRatesUrl,
                json: true
            });
        } catch (e) {
            logger.error(e, 'Error getting exchange rate info');
            res.locals.exchangeRates = null;

            return next();
        }

        if (!ratesResponse.rates) {
            // Something is wrong with the response
            logger.error('Malformed exchange rates response');
            res.locals.exchangeRates = null;

            return next();
        }

        try {
            yield insertInDb({
                collection: exchangeRatesCollection,
                document: {
                    validOn: moment().startOf('day').toDate(),
                    ...ratesResponse
                }
            });
        } catch (e) {
            logger.error(e, 'Error saving exchange rate info to db');
            res.locals.exchangeRates = null;

            return next();
        }

        rates = ratesResponse.rates;
    }

    res.locals.exchangeRates = rates;

    return next();
});<commit_msg>Integrated the new fixer api after the deprecation of the old one<commit_after>// This module provides middleware that loads currency conversion information into
// res.locals. It fetches this information from the db. The db should be refreshed everyday
// with this information so if the data is old, this middleware will make a request
// for fresh information, save it to the db, and then populate it in res.locals

import { wrap as coroutine } from 'co';
import request from 'request-promise';
import moment from 'moment';

import { required, print } from '../custom-utils';
import { getCurrentExchangeRates } from '../data';
import { insert as insertInDb } from '../db/service';

export default ({
    exchangeRatesCollection = required('exchangeRatesCollection'),
    logger = required('logger', 'You must pass in a logging instance for this api to use')
}) => coroutine(function* (req, res, next) {
    const {
        exchangeRates: {
            reqUrl: exchangeRatesUrl
        } = {}
    } = res.locals.config;

    if (!exchangeRatesUrl) {
        throw new Error('Missing exchange rates url from config');
    }

    let rates;

    // First, see if there are fresh rates in the db
    try {
        rates = yield getCurrentExchangeRates({ exchangeRatesCollection });
    } catch (e) {
        logger.error(e.err, e.msg);
        res.locals.exchangeRates = null;

        return next();
    }

    if (!rates) {
        // We need to fetch current rates and save them to the db
        let ratesResponse;

        try {
            ratesResponse = yield request({
                uri: exchangeRatesUrl,
                json: true
            });
        } catch (e) {
            logger.error(e, 'Error getting exchange rate info');
            res.locals.exchangeRates = null;

            return next();
        }

        if (!ratesResponse.rates) {
            // Something is wrong with the response
            logger.error('Malformed exchange rates response');
            res.locals.exchangeRates = null;

            return next();
        }

        // We are only getting the rates in base EUR, so convert them to base CAD by dividing the base EUR rate by the base EUR rate for CAD
        const {
            rates: {
                CAD: eurToCad
            } = {}
        } = ratesResponse;

        const cadRates = Object.keys(ratesResponse.rates).reduce((accumulator, key) => {
            if (key == 'CAD') {
                return accumulator;
            } else if (key == 'EUR') {
                accumulator[key] = 1.0 / eurToCad
            } else {
                accumulator[key] = ratesResponse.rates[key] / eurToCad;
            }

            return accumulator;
        }, {});

        try {
            yield insertInDb({
                collection: exchangeRatesCollection,
                document: {
                    ...ratesResponse,
                    validOn: moment().startOf('day').toDate(),
                    rates: cadRates,
                    base: 'CAD'
                }
            });
        } catch (e) {
            logger.error(e, 'Error saving exchange rate info to db');
            res.locals.exchangeRates = null;

            return next();
        }

        rates = cadRates;
    }

    res.locals.exchangeRates = rates;

    return next();
});
{'fraction_non_alphanumeric': 0.09817934320231411, 'fraction_numerical': 0.0003403096818104475, 'mean_word_length': 1.8603406326034064, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 6, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '246928', 'n_tokens_mistral': 1575, 'n_tokens_neox': 1483, 'n_words': 522}