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

42.86% Statements 12/28
0% Branches 0/6
66.67% Functions 2/3
46.15% Lines 12/26
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                                                                                                   
"use strict";
 
const hl = require('highland');
const R = require('ramda');
const mapper = require('../../toJSON/mapper');
const stitcher = require('../../toJSON/stitcher');
const articleQuery = require('../../query/article');
const createParallelRequests = require('../get');
 
function getWidgetIds(config, source, publicationId) {
    return R.defaultTo(config.widgetIds.default, R.path(['widgetIds', source, publicationId], config));
}
 
module.exports = (db, config, logger, source, publicationId) => hl.wrapCallback((escenicId, cb) => {
 
    const id = `${source}.${escenicId}`;
 
    const articleNotFound = hl((push) => {
        push({
            "message": `${source}/${publicationId}/articles/${escenicId} not available`,
            "status": "NotFoundError"
        });
    });
 
    const query = articleQuery(db, id);
 
    logger.time('finished postgres db request');
 
    hl(db.article.find(query))
        .tap(() => logger.timeEnd('finished postgres db request'))
        .reject(R.isNil)
        .otherwise(articleNotFound)
        .map(removeIsNilArticleContents)
        .flatMap(createParallelRequests(db, config))
        .sequence()
        .reject(R.isEmpty)
        .map(getPlainTrueIfSequelizeInstance)
        .map(mapper({
            imageDimensions: config.imageDimensions,
            widgetIds: getWidgetIds(config, source, publicationId)
        }))
        .tap(tuple => {
            const error = R.path([0, "error"], tuple);
            if(error) logger.warning("API non critical error", error);
        })
        .collect()
        .map(stitcher)
        .toCallback(cb);
});
 
function getPlainTrueIfSequelizeInstance(tuple) {
    const obj = R.last(tuple);
    const type = R.head(tuple);
    if(!R.isNil(obj.get) && typeof obj.get === "function") {
        return [type, obj.get({"plain": true})];
    }
    return [type, obj];
}
 
function removeIsNilArticleContents(articleInstance) {
    return R.assoc('article_contents', R.reject(R.isNil, articleInstance.article_contents), articleInstance);
}