all files / api/toJSON/ image.js

100% Statements 25/25
91.67% Branches 11/12
100% Functions 2/2
100% Lines 23/23
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 64 65 66 67 68 69 70 71                                                                            23×                 12× 12×    
'use strict';
 
const R = require('ramda');
const createSection = require('./section');
const config = require('config');
const imageService = config.imageService;
 
module.exports = R.curry((imageDimensions, tuple) => {
    let image = tuple[1];
 
    if(R.isNil(image.home_section)) return null;
 
    const homeSection = createSection(image.home_section);
 
    if(R.has('article_relations', image) && image.article_relations.length > 0){
        image = R.merge(image, image.article_relations[0].static_content);
    }
 
    const imageObject =  {
        data: {
            type: 'image',
            id: image.escenic_id,
            attributes: {
                imageCredit: image.image_credit,
                width: imageDimensions.width,
                height: imageDimensions.height,
                altText: image.alttext,
                caption: image.caption,
                title: image.title,
                alternates: buildAlternates(config.cropsWhitelist, image.alternates)
            },
            links: {
                url: createImageUrl(image, homeSection, imageDimensions.code),
                thumbnailUrl: createImageUrl(image, homeSection, 's338b'),
                templateUrl: createImageUrl(image, homeSection, '%s')
            }
        }
    };
 
    const meta = R.merge(tuple[0], {
        "type": "image",
        "lastModifiedDate": image.last_modified_date || image.updated_at,
        "id": image.id
    });
 
    return Array.of(meta, imageObject);
 
});
 
function buildAlternates(allowedCrops, alternates) {
 
    if (R.isNil(alternates)) return null;
 
    const isWhitelistedCrop = R.flip(R.contains)(allowedCrops);
    const crops = R.filter(isWhitelistedCrop, R.keys(alternates));
    const cropsList = R.reduce((mem, crop) => {
        return R.append({
            crop: crop,
            height: R.path([crop, 'output', 'height'], alternates),
            width: R.path([crop, 'output', 'width'], alternates)
        }, mem);
    }, [], crops);
 
    return R.isEmpty(cropsList) ? null : cropsList;
}
 
function createImageUrl(image, homeSection, code) {
    const secureHost = R.replace(/http:\/\/www\d?/, `https://${imageService}`, homeSection.url);
    return `${secureHost}${image.file_name}/ALTERNATES/${code}/${image.title}`;
}