node-screener icon indicating copy to clipboard operation
node-screener copied to clipboard

Default value for empty array

Open Prinzhorn opened this issue 12 years ago • 1 comments

Thanks for creating screener, I'm using it for our mobile API.

I have an offer object and my filter looks like this

module.exports = {
    _id: true,
    title: true,
    body: true,
    location: true,
    images: [require('../image')]
};

and image looks like

var models = require('models');

module.exports = function(object) {
    return models.Image.getUrl(object);
};

It's working perfectly and transforms the array of image _ids into an array of Strings (the URLs of the images).

Now the thing is I'd like to have at least one image inside the array. That means if the offer object does not have any images (empty array), then I want to react and fill it with the URL of the default image.

It would be great if there's a way to do this with screener as I'd like to keep the logic away from the controller.

Prinzhorn avatar Sep 08 '13 11:09 Prinzhorn

I've now solved it like this

module.exports = {
    _id: true,
    title: true,
    body: true,
    location: true,
    images: require('../imageList')
};

imageList.js

var imageFilter = require('./image');

module.exports = function(images) {
    if(!images.length) {
        return [imageFilter('default')];
    }

    return images.map(function(image) {
        return imageFilter(image);
    });
};

image.js

var models = require('models');

module.exports = function(_id) {
    return models.Image.getUrl(_id);
};

Tell me if there's a nicer solution. If not I can live with what I have now.

Prinzhorn avatar Sep 08 '13 14:09 Prinzhorn