all files / api/lib/get/ authorsEndpoint.js

90.91% Statements 30/33
75% Branches 12/16
100% Functions 2/2
90.63% Lines 29/32
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63                                                                   
'use strict';
 
const R = require('ramda');
let request = require('superagent');
 
module.exports = (config, articleAuthors) => {
    Eif (!R.isNil(articleAuthors) && articleAuthors.length > 0) {
        const authors = R.pluck("dataValues", articleAuthors)
            .map(x => R.assoc("id", x.author_id, x));
 
        return new Promise(resolve => {
            requestAuthors(config, authors, resolve);
        });
    }
    return Promise.resolve([]);
};
 
function groupAuthors(authors) {
    return R.reduce((mem, author) => {
        const hasId = R.compose(R.not, R.isNil, R.prop('id'))(author);
        Eif (hasId) {
            return R.assoc('withIds', R.concat(mem.withIds, R.of(author)), mem);
        }
        return R.assoc('withoutIds', R.concat(mem.withoutIds, R.of(author)), mem);
    }, {withIds: [], withoutIds: []}, authors);
}
 
function requestAuthors(config, authors, cb) {
    const meta = R.objOf("type", "author");
    const groupedAuthors = groupAuthors(authors);
 
    request
        .get(config.authorsEndpoint)
        .query({
            "ids": R.pluck('id', groupedAuthors.withIds)
        })
        .timeout(250)
        .end((err, res) => {
 
            if (err || res.error) {
                const error = R.map(R.pair(R.assoc("error", res ? res.body : err, meta)), authors);
                return cb(error);
            }
            
            if (R.isEmpty(res.body)){
                const defaultError = {
                    code : 'NotFoundError',
                    message: 'No genuine IDs were given in query string'
                };
                const error = R.map(R.pair(R.assoc("error", defaultError, meta)), authors);
                return cb(error);
            }
 
            const authorsTuplesWithoutIds = R.map(R.pair(meta), groupedAuthors.withoutIds);
            const authorsTuplesFromApi = groupedAuthors.withIds.map(author => {
                const serviceAuthor = R.find(R.propEq("id", author.id), res.body);
                Eif (serviceAuthor) return [meta, R.merge(author, serviceAuthor)];
                return [meta, author];
            });
 
            cb(R.concat(authorsTuplesFromApi, authorsTuplesWithoutIds));
        });
}