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
} = require("lodash/fp");

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

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

exports.createModel = (model) => ({
    /**
     * State model initializer
     * @param {Object|Array} value - Value to initialize model with (default
     * is empty object {})
     * @return {Void} Nothing
     */
    init: (value) => state.set(model)(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 {Any} Value located at id for the given model
     */
    getById: (id) => state.get(`${model}.${id}`),

    /**
     * Add a new entity to the current State
     * @return {Function} Function that will update model content for a new id
     */
    add: (value) => flow(
        utils.getUniqueId,
        (id) => state.set(`${model}.${id}`)(value)
    )(),

    /**
     * State model updater by related id
     * @param {String} id - Id to retrieve
     * @return {Function} Function that will update content for given id
     */
    updateById: (id) => state.update(`${model}.${id}`),

    /**
     * State model deleter 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))
});