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

71.43% Statements 20/28
57.14% Branches 8/14
100% Functions 2/2
74.07% Lines 20/27
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      27× 11× 11×   11× 11×     16×     11× 11× 11× 11×           11× 11×   11×             11× 11×                        
'use strict';
 
const R = require('ramda');
let request = require('superagent');
 
module.exports = (config, articleAuthors) => {
    if (!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) => {
            Eif (err || res.error) {
                return cb(R.map(R.pair(R.assoc("error", res ? res.body : err, meta)), authors));
            }
 
            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);
                if (serviceAuthor) return [meta, R.merge(author, serviceAuthor)];
                return [meta, author];
            });
 
            cb(R.concat(authorsTuplesFromApi, authorsTuplesWithoutIds));
        });
}