/**
* ### Entities functions
*
* Common functions that will be available on all entities
*
* @module Models/Entities
*/
"use strict";
const path = require("path");
const {
assign,
filter,
find,
flow,
map,
union
} = require("lodash/fp");
const utils = require(path.resolve(__dirname, "../lib/utils"));
const state = require(utils.getModulePath("lib/state"));
state.set("entities", []);
/**
* Retrieve all entities
* Not very useful for the moment...but will be more fun when I add filters and
* such :D
* @param {Object} state - Current State
* @return {Array<Object>} Entity list
*/
exports.getAll = (state) => state.get("entities");
/**
* Full refresh of entities
* @curried
* @param {Object} state - Current State
* @param {Array<Object>} entities - New entities list
* @return {Object} New entities list
*/
exports.fullRefresh = (state) => function(entities) {
// Start with flushing State entities list
state.set("entities", []);
// For every entity in the given entities list, add it to State
return map(exports.add(state), entities);
};
/**
* Add a new entity to the current State
* @curried
* @param {Object} state - Current state
* @param {Object} entity - New entity
* @return {Object} New entity
*/
exports.add = (state) => function(entity) {
const entities = state.get("entities");
const newEntity = assign(entity, {});
newEntity.id = newEntity.id || entities.length;
state.set("entities", union(entities, [newEntity]));
return newEntity;
};
/**
* Retrieve an entity
* @curried
* @param {Object} state - Current State
* @param {Number} entityId - Entity id
* @return {Object} Retrieved entity
*/
exports.get = (state) => (entityId) => filter({
id: entityId
}, state.get("entities"))[0];
/**
* Delete an entity
* @curried
* @param {Object} state - Current State
* @param {Number} removedEntity - Entity to remove
* @return {Object} Removed entity
*/
exports.remove = (state) => function(removedEntity) {
const entities = state.get("entities");
state.set("entities", filter(
(entity) => entity.id !== removedEntity.id,
entities));
return removedEntity;
};
/**
* Update an entity
* @curried
* @param {Object} state - Current State
* @param {Number} removedId - Entity id to remove
* @return {Object} Removed entity
*/
exports.update = (state) => (updatedId, updatedProperties) =>
flow(
// Focus on the entity we want to update
(entities) => filter((entity) => (entity.id === updatedId), entities)[0],
// Overload entity properties with given ones
(entity) => assign(entity, updatedProperties),
// Remove and then add the entity back to update State
exports.remove(state),
exports.add(state)
)
// Start with entities list
(state.get("entities"));
/**
* Delete an entity by its id
* @curried
* @param {Object} state - Current State
* @param {Number} removedId - Entity id to remove
* @return {Object} Removed entity
*/
exports.removeById = (state) => function(removedId) {
const removedEntity = find({
id: removedId
}, state.get("entities"));
return exports.remove(state)(removedEntity);
};