Source: models/factory.js

/**
 * ### Model factory
 *
 * All common model logic (CRUD) is factored in this model factory
 * Models are stored in State to defer all side-effects in a single place
 *
 * @module Model/Common
 */
"use strict";

const path = require("path");

const {
    flow,
    has,
    isArray,
    isObject,
    map,
    mapKeys
} = require("lodash/fp");

const utils = require(path.resolve(__dirname, "../lib/utils"));

const state = require(utils.getModulePath("lib/state"));

/**
 * Check if an object is a reference object (i.e { references: [...] })
 * named "references"
 * @param {Object} input - Object to parse
 * @return {Boolean} True if given input is an object which only has one property named "references"
 */
exports.isReferenceObject = (input) =>
    isObject(input) &&
    has("references", input) &&
    Object.keys(input).length === 1 &&
    isArray(input.references);

/**
 * Reference resolver. References are exported as "references" properties with string
 * array values. Theses strings are references to keys in the main object.
 * This function replaces all these strings references by real ones.
 * WARNING: To ensure proper circular references, object are mutated (this
 * allows keeping references untouched when parsing the tree)
 * @recursive
 * @param {Object} input - Object to parse
 * @param {Object} topObject - Reference to the top object
 * @return {Object} Input copy that has all references resolved
 */
exports.resolveReferences = function(input, topRef) {
    // Convenience to avoid having to make the first call with the same
    // parameter twice
    const topObject = topRef || input;
    if (isArray(input)) {
        return map((value) => exports.resolveReferences(value, topObject), input);
    }

    if (exports.isReferenceObject(input)) {
        return map((ref) => topObject[ref], input.references);
    }

    if (!exports.isReferenceObject(input) && isObject(input)) {
        mapKeys(function(property) {
            input[property] = exports.resolveReferences(
                input[property],
                topObject
            );
        }, input);
        return input;
    }

    return input;
};

exports.createModel = (model) => ({
    /**
     * State model initializer. Given value has its references resolved against
     * the state model during the process.
     * @param {Mixed} value - Value to initialize model with (default
     * is empty object {})
     * @return {Void} Nothing
     */
    init: (value) => state.set(model)(exports.resolveReferences(value) || {}),

    /**
     * Retrieve all entities
     * Not very useful for the moment...but will be more fun when I add filters and
     * such :D
     * @return {Array<Object>} Entity list
     */
    getAll: () => state.get(model),

    /**
     * State model getter by related id
     * @param {String} id - Id to retrieve
     * @return {Mixed} Item located at id for the given model
     */
    getById: (id) => state.get(`${model}.${id}`),

    /**
     * Add a new item to the State model, its unique id will be generated on the fly.
     * @param {Mixed} item - item to add
     * @return {Void} Nothing
     */
    add: (item) => flow(
        utils.getUniqueId,
        // References are resolved against the main model State
        (id) => state.set(`${model}.${id}`)(
            exports.resolveReferences(item, state.get(model))
        )
    )(),

    /**
     * State model updater by related id. Only the given properties will be
     * updated, and the update will only occur if the item id exists in State
     * @param {String} id - Id of the item that will be updated
     * @param {Object} properties - Properties that will be updated
     * @return {Void} Nothing
     */
    updateById: (id) => (value) => state.update(`${model}.${id}`)(
        exports.resolveReferences(value, state.get(model))
    ),

    /**
     * State model remover by related id
     * @param {String} id - Id to remove
     * @return {Function} Function that will remove content for given id
     */
    removeById: (id) => flow(
        function(a) {
            const b = Object.assign({}, a);
            if (b[id]) {
                delete b[id];
            }
            return b;
        },
        state.set(model)
    )(state.get(model))
});