@ngxs-labs/entity-state
Version:
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 7.0.5.
1,514 lines (1,499 loc) • 56.8 kB
JavaScript
import { __extends, __spread, __assign } from 'tslib';
import { ofAction, ofActionCompleted, ofActionDispatched, ofActionErrored, ofActionSuccessful } from '@ngxs/store';
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
var EntityStateError = /** @class */ (function (_super) {
__extends(EntityStateError, _super);
function EntityStateError(message) {
return _super.call(this, message) || this;
}
return EntityStateError;
}(Error));
var NoActiveEntityError = /** @class */ (function (_super) {
__extends(NoActiveEntityError, _super);
function NoActiveEntityError(additionalInformation) {
if (additionalInformation === void 0) { additionalInformation = ''; }
return _super.call(this, ('No active entity to affect. ' + additionalInformation).trim()) || this;
}
return NoActiveEntityError;
}(EntityStateError));
var NoSuchEntityError = /** @class */ (function (_super) {
__extends(NoSuchEntityError, _super);
function NoSuchEntityError(id) {
return _super.call(this, "No entity for ID " + id) || this;
}
return NoSuchEntityError;
}(EntityStateError));
var InvalidIdError = /** @class */ (function (_super) {
__extends(InvalidIdError, _super);
function InvalidIdError(id) {
return _super.call(this, "Invalid ID: " + id) || this;
}
return InvalidIdError;
}(EntityStateError));
var InvalidIdOfError = /** @class */ (function (_super) {
__extends(InvalidIdOfError, _super);
function InvalidIdOfError() {
return _super.call(this, "idOf returned undefined") || this;
}
return InvalidIdOfError;
}(EntityStateError));
var UpdateFailedError = /** @class */ (function (_super) {
__extends(UpdateFailedError, _super);
function UpdateFailedError(cause) {
return _super.call(this, "Updating entity failed.\n\tCause: " + cause) || this;
}
return UpdateFailedError;
}(EntityStateError));
var UnableToGenerateIdError = /** @class */ (function (_super) {
__extends(UnableToGenerateIdError, _super);
function UnableToGenerateIdError(cause) {
return _super.call(this, "Unable to generate an ID.\n\tCause: " + cause) || this;
}
return UnableToGenerateIdError;
}(EntityStateError));
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @type {?} */
var NGXS_META_KEY = 'NGXS_META';
/**
* This function generates a new object for the ngxs Action with the given fn name
* @template T
* @param {?} fn The name of the Action to simulate, e.g. "Remove" or "Update"
* @param {?} store The class of the targeted entity state, e.g. ZooState
* @param {?=} payload The payload for the created action object
* @return {?}
*/
function generateActionObject(fn, store, payload) {
/** @type {?} */
var name = store[NGXS_META_KEY].path;
/** @type {?} */
var ReflectedAction = (/**
* @param {?} data
* @return {?}
*/
function (data) {
this.payload = data;
});
/** @type {?} */
var obj = new ReflectedAction(payload);
Reflect.getPrototypeOf(obj).constructor['type'] = "[" + name + "] " + fn;
return obj;
}
/**
* Utility function that returns the active entity of the given state
* @template T
* @param {?} state the state of an entity state
* @return {?}
*/
function getActive(state) {
return state.entities[state.active];
}
/**
* Returns the active entity. If none is present an error will be thrown.
* @template T
* @param {?} state The state to act on
* @return {?}
*/
function mustGetActive(state) {
/** @type {?} */
var active = getActive(state);
if (active === undefined) {
throw new NoActiveEntityError();
}
return { id: state.active, active: active };
}
/**
* Undefined-safe function to access the property given by path parameter
* @param {?} object The object to read from
* @param {?} path The path to the property
* @return {?}
*/
function elvis(object, path) {
return path ? path.split('.').reduce((/**
* @param {?} value
* @param {?} key
* @return {?}
*/
function (value, key) { return value && value[key]; }), object) : object;
}
/**
* Returns input as an array if it isn't one already
* @template T
* @param {?} input The input to make an array if necessary
* @return {?}
*/
function asArray(input) {
return Array.isArray(input) ? input : [input];
}
/**
* Limits a number to the given boundaries
* @param {?} value The input value
* @param {?} min The minimum value
* @param {?} max The maximum value
* @return {?}
*/
function clamp(value, min, max) {
return Math.min(max, Math.max(min, value));
}
/**
* Uses the clamp function is wrap is false.
* Else it wrap to the max or min value respectively.
* @param {?} wrap Flag to indicate if value should be wrapped
* @param {?} value The input value
* @param {?} min The minimum value
* @param {?} max The maximum value
* @return {?}
*/
function wrapOrClamp(wrap, value, min, max) {
if (!wrap) {
return clamp(value, min, max);
}
else if (value < min) {
return max;
}
else if (value > max) {
return min;
}
else {
return value;
}
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @enum {string} */
var EntityActionType = {
Add: 'add',
CreateOrReplace: 'createOrReplace',
Update: 'update',
UpdateActive: 'updateActive',
Remove: 'remove',
RemoveActive: 'removeActive',
SetLoading: 'setLoading',
SetError: 'setError',
SetActive: 'setActive',
ClearActive: 'clearActive',
Reset: 'reset',
GoToPage: 'goToPage',
SetPageSize: 'setPageSize',
};
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @template T
*/
var /**
* @template T
*/
Add = /** @class */ (function () {
/**
* Generates an action that will add the given entities to the state.
* The entities given by the payload will be added.
* For certain ID strategies this might fail, if it provides an existing ID.
* In all other cases it will overwrite the ID value in the entity with the calculated ID.
* @param target The targeted state class
* @param payload An entity or an array of entities to be added
* @see CreateOrReplace#constructor
*/
function Add(target, payload) {
return generateActionObject(EntityActionType.Add, target, payload);
}
return Add;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @template T
*/
var /**
* @template T
*/
CreateOrReplace = /** @class */ (function () {
/**
* Generates an action that will add the given entities to the state.
* If an entity with the ID already exists, it will be overridden.
* In all cases it will overwrite the ID value in the entity with the calculated ID.
* @param target The targeted state class
* @param payload An entity or an array of entities to be added
* @see Add#constructor
*/
function CreateOrReplace(target, payload) {
return generateActionObject(EntityActionType.CreateOrReplace, target, payload);
}
return CreateOrReplace;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @template T
*/
var /**
* @template T
*/
Remove = /** @class */ (function () {
/**
* Generates an action that will remove the given entities from the state.
* Put null if all entities should be removed.
* @param target The targeted state class
* @param payload An EntitySelector payload
* @see EntitySelector
*/
function Remove(target, payload) {
return generateActionObject(EntityActionType.Remove, target, payload);
}
return Remove;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @template T
*/
var /**
* @template T
*/
Update = /** @class */ (function () {
/**
* Generates an action that will update the current active entity.
* If no entity is active a runtime error will be thrown.
* @param target The targeted state class
* @param id An EntitySelector that determines the entities to update
* @param data An Updater that will be applied to the selected entities
* @see EntitySelector
* @see Updater
*/
function Update(target, id, data) {
return generateActionObject(EntityActionType.Update, target, { id: id, data: data });
}
return Update;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
var SetLoading = /** @class */ (function () {
/**
* Generates an action that will set the loading state for the given state.
* @param target The targeted state class
* @param loading The loading state
*/
function SetLoading(target, loading) {
return generateActionObject(EntityActionType.SetLoading, target, loading);
}
return SetLoading;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
var SetActive = /** @class */ (function () {
/**
* Generates an action that sets an ID that identifies the active entity
* @param target The targeted state class
* @param id The ID that identifies the active entity
*/
function SetActive(target, id) {
return generateActionObject(EntityActionType.SetActive, target, id);
}
return SetActive;
}());
var ClearActive = /** @class */ (function () {
/**
* Generates an action that clears the active entity in the given state
* @param target The targeted state class
*/
function ClearActive(target) {
return generateActionObject(EntityActionType.ClearActive, target);
}
return ClearActive;
}());
var RemoveActive = /** @class */ (function () {
/**
* Generates an action that removes the active entity from the state and clears the active ID.
* @param target The targeted state class
*/
function RemoveActive(target) {
return generateActionObject(EntityActionType.RemoveActive, target);
}
return RemoveActive;
}());
/**
* @template T
*/
var /**
* @template T
*/
UpdateActive = /** @class */ (function () {
/**
* Generates an action that will update the current active entity.
* If no entity is active a runtime error will be thrown.
* @param target The targeted state class
* @param payload An Updater payload
* @see Updater
*/
function UpdateActive(target, payload) {
return generateActionObject(EntityActionType.UpdateActive, target, payload);
}
return UpdateActive;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
var SetError = /** @class */ (function () {
/**
* Generates an action that will set the error state for the given state.
* Put undefined to clear the error state.
* @param target The targeted state class
* @param error The error that describes the error state
*/
function SetError(target, error) {
return generateActionObject(EntityActionType.SetError, target, error);
}
return SetError;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
var Reset = /** @class */ (function () {
/**
* Resets the targeted store to the default state: no entities, loading is false, error is undefined, active is undefined.
* @param target The targeted state class
* @see defaultEntityState
*/
function Reset(target) {
return generateActionObject(EntityActionType.Reset, target);
}
return Reset;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
var GoToPage = /** @class */ (function () {
/**
* Generates an action that changes the page index for pagination.
* Page index starts at 0.
* @param target The targeted state class
* @param payload Payload to change the page index
*/
function GoToPage(target, payload) {
return generateActionObject(EntityActionType.GoToPage, target, __assign({ wrap: false }, payload));
}
return GoToPage;
}());
var SetPageSize = /** @class */ (function () {
/**
* Generates an action that changes the page size
* @param target The targeted state class
* @param payload The page size
*/
function SetPageSize(target, payload) {
return generateActionObject(EntityActionType.SetPageSize, target, payload);
}
return SetPageSize;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Returns a new object which serves as the default state.
* No entities, loading is false, error is undefined, active is undefined.
* pageSize is 10 and pageIndex is 0.
* @template T
* @param {?=} defaults
* @return {?}
*/
function defaultEntityState(defaults) {
if (defaults === void 0) { defaults = {}; }
return __assign({ entities: {}, ids: [], loading: false, error: undefined, active: undefined, pageSize: 10, pageIndex: 0, lastUpdated: Date.now() }, defaults);
}
// @dynamic
/**
* @abstract
* @template T
*/
var
// @dynamic
/**
* @abstract
* @template T
*/
EntityState = /** @class */ (function () {
function EntityState(storeClass, _idKey, idStrategy) {
this.idKey = (/** @type {?} */ (_idKey));
this.storePath = storeClass[NGXS_META_KEY].path;
this.idGenerator = new idStrategy(_idKey);
this.setup(storeClass, Object.values(EntityActionType));
}
Object.defineProperty(EntityState, "staticStorePath", {
get: /**
* @private
* @return {?}
*/
function () {
/** @type {?} */
var that = this;
return that[NGXS_META_KEY].path;
},
enumerable: true,
configurable: true
});
/**
* This function is called every time an entity is updated.
* It receives the current entity and a partial entity that was either passed directly or generated with a function.
* The default implementation uses the spread operator to create a new entity.
* You must override this method if your entity type does not support the spread operator.
* @see Updater
* @param current The current entity, readonly
* @param updated The new data as a partial entity
* @example
* // default behavior
* onUpdate(current: Readonly<T updated: Partial<T>): T {
return {...current, ...updated};
}
*/
/**
* This function is called every time an entity is updated.
* It receives the current entity and a partial entity that was either passed directly or generated with a function.
* The default implementation uses the spread operator to create a new entity.
* You must override this method if your entity type does not support the spread operator.
* @see Updater
* \@example
* // default behavior
* onUpdate(current: Readonly<T updated: Partial<T>): T {
* return {...current, ...updated};
* }
* @param {?} current The current entity, readonly
* @param {?} updated The new data as a partial entity
* @return {?}
*/
EntityState.prototype.onUpdate = /**
* This function is called every time an entity is updated.
* It receives the current entity and a partial entity that was either passed directly or generated with a function.
* The default implementation uses the spread operator to create a new entity.
* You must override this method if your entity type does not support the spread operator.
* @see Updater
* \@example
* // default behavior
* onUpdate(current: Readonly<T updated: Partial<T>): T {
* return {...current, ...updated};
* }
* @param {?} current The current entity, readonly
* @param {?} updated The new data as a partial entity
* @return {?}
*/
function (current, updated) {
return (/** @type {?} */ (__assign({}, current, updated)));
};
Object.defineProperty(EntityState, "activeId", {
// ------------------- SELECTORS -------------------
/**
* Returns a selector for the activeId
*/
get:
// ------------------- SELECTORS -------------------
/**
* Returns a selector for the activeId
* @return {?}
*/
function () {
/** @type {?} */
var that = this;
return (/**
* @param {?} state
* @return {?}
*/
function (state) {
/** @type {?} */
var subState = (/** @type {?} */ (elvis(state, that.staticStorePath)));
return subState.active;
});
},
enumerable: true,
configurable: true
});
Object.defineProperty(EntityState, "active", {
/**
* Returns a selector for the active entity
*/
get: /**
* Returns a selector for the active entity
* @return {?}
*/
function () {
/** @type {?} */
var that = this;
return (/**
* @param {?} state
* @return {?}
*/
function (state) {
/** @type {?} */
var subState = (/** @type {?} */ (elvis(state, that.staticStorePath)));
return getActive(subState);
});
},
enumerable: true,
configurable: true
});
Object.defineProperty(EntityState, "keys", {
/**
* Returns a selector for the keys of all entities
*/
get: /**
* Returns a selector for the keys of all entities
* @return {?}
*/
function () {
/** @type {?} */
var that = this;
return (/**
* @param {?} state
* @return {?}
*/
function (state) {
/** @type {?} */
var subState = (/** @type {?} */ (elvis(state, that.staticStorePath)));
return Object.keys(subState.entities);
});
},
enumerable: true,
configurable: true
});
Object.defineProperty(EntityState, "entities", {
/**
* Returns a selector for all entities, sorted by insertion order
*/
get: /**
* Returns a selector for all entities, sorted by insertion order
* @return {?}
*/
function () {
/** @type {?} */
var that = this;
return (/**
* @param {?} state
* @return {?}
*/
function (state) {
/** @type {?} */
var subState = (/** @type {?} */ (elvis(state, that.staticStorePath)));
return subState.ids.map((/**
* @param {?} id
* @return {?}
*/
function (id) { return subState.entities[id]; }));
});
},
enumerable: true,
configurable: true
});
/**
* Returns a selector for the nth entity, sorted by insertion order
*/
/**
* Returns a selector for the nth entity, sorted by insertion order
* @param {?} index
* @return {?}
*/
EntityState.nthEntity = /**
* Returns a selector for the nth entity, sorted by insertion order
* @param {?} index
* @return {?}
*/
function (index) {
// tslint:disable-line:member-ordering
/** @type {?} */
var that = this;
return (/**
* @param {?} state
* @return {?}
*/
function (state) {
/** @type {?} */
var subState = (/** @type {?} */ (elvis(state, that.staticStorePath)));
/** @type {?} */
var id = subState.ids[index];
return subState.entities[id];
});
};
Object.defineProperty(EntityState, "paginatedEntities", {
/**
* Returns a selector for paginated entities, sorted by insertion order
*/
get: /**
* Returns a selector for paginated entities, sorted by insertion order
* @return {?}
*/
function () {
// tslint:disable-line:member-ordering
/** @type {?} */
var that = this;
return (/**
* @param {?} state
* @return {?}
*/
function (state) {
/** @type {?} */
var subState = (/** @type {?} */ (elvis(state, that.staticStorePath)));
var ids = subState.ids, pageIndex = subState.pageIndex, pageSize = subState.pageSize;
return ids
.slice(pageIndex * pageSize, (pageIndex + 1) * pageSize)
.map((/**
* @param {?} id
* @return {?}
*/
function (id) { return subState.entities[id]; }));
});
},
enumerable: true,
configurable: true
});
Object.defineProperty(EntityState, "entitiesMap", {
/**
* Returns a selector for the map of entities
*/
get: /**
* Returns a selector for the map of entities
* @return {?}
*/
function () {
/** @type {?} */
var that = this;
return (/**
* @param {?} state
* @return {?}
*/
function (state) {
/** @type {?} */
var subState = (/** @type {?} */ (elvis(state, that.staticStorePath)));
return subState.entities;
});
},
enumerable: true,
configurable: true
});
Object.defineProperty(EntityState, "size", {
/**
* Returns a selector for the size of the entity map
*/
get: /**
* Returns a selector for the size of the entity map
* @return {?}
*/
function () {
/** @type {?} */
var that = this;
return (/**
* @param {?} state
* @return {?}
*/
function (state) {
/** @type {?} */
var subState = (/** @type {?} */ (elvis(state, that.staticStorePath)));
return Object.keys(subState.entities).length;
});
},
enumerable: true,
configurable: true
});
Object.defineProperty(EntityState, "error", {
/**
* Returns a selector for the error
*/
get: /**
* Returns a selector for the error
* @return {?}
*/
function () {
/** @type {?} */
var that = this;
return (/**
* @param {?} state
* @return {?}
*/
function (state) {
/** @type {?} */
var name = that.staticStorePath;
return elvis(state, name).error;
});
},
enumerable: true,
configurable: true
});
Object.defineProperty(EntityState, "loading", {
/**
* Returns a selector for the loading state
*/
get: /**
* Returns a selector for the loading state
* @return {?}
*/
function () {
/** @type {?} */
var that = this;
return (/**
* @param {?} state
* @return {?}
*/
function (state) {
/** @type {?} */
var name = that.staticStorePath;
return elvis(state, name).loading;
});
},
enumerable: true,
configurable: true
});
Object.defineProperty(EntityState, "latest", {
/**
* Returns a selector for the latest added entity
*/
get: /**
* Returns a selector for the latest added entity
* @return {?}
*/
function () {
/** @type {?} */
var that = this;
return (/**
* @param {?} state
* @return {?}
*/
function (state) {
/** @type {?} */
var subState = (/** @type {?} */ (elvis(state, that.staticStorePath)));
/** @type {?} */
var latestId = subState.ids[subState.ids.length - 1];
return subState.entities[latestId];
});
},
enumerable: true,
configurable: true
});
Object.defineProperty(EntityState, "latestId", {
/**
* Returns a selector for the latest added entity id
*/
get: /**
* Returns a selector for the latest added entity id
* @return {?}
*/
function () {
/** @type {?} */
var that = this;
return (/**
* @param {?} state
* @return {?}
*/
function (state) {
/** @type {?} */
var subState = (/** @type {?} */ (elvis(state, that.staticStorePath)));
return subState.ids[subState.ids.length - 1];
});
},
enumerable: true,
configurable: true
});
Object.defineProperty(EntityState, "lastUpdated", {
/**
* Returns a selector for the update timestamp
*/
get: /**
* Returns a selector for the update timestamp
* @return {?}
*/
function () {
// tslint:disable-line:member-ordering
/** @type {?} */
var that = this;
return (/**
* @param {?} state
* @return {?}
*/
function (state) {
/** @type {?} */
var subState = (/** @type {?} */ (elvis(state, that.staticStorePath)));
return new Date(subState.lastUpdated);
});
},
enumerable: true,
configurable: true
});
Object.defineProperty(EntityState, "age", {
/**
* Returns a selector for age, based on the update timestamp
*/
get: /**
* Returns a selector for age, based on the update timestamp
* @return {?}
*/
function () {
// tslint:disable-line:member-ordering
/** @type {?} */
var that = this;
return (/**
* @param {?} state
* @return {?}
*/
function (state) {
/** @type {?} */
var subState = (/** @type {?} */ (elvis(state, that.staticStorePath)));
return Date.now() - subState.lastUpdated;
});
},
enumerable: true,
configurable: true
});
// ------------------- ACTION HANDLERS -------------------
/**
* The entities given by the payload will be added.
* For certain ID strategies this might fail, if it provides an existing ID.
* In all cases it will overwrite the ID value in the entity with the calculated ID.
*/
// ------------------- ACTION HANDLERS -------------------
/**
* The entities given by the payload will be added.
* For certain ID strategies this might fail, if it provides an existing ID.
* In all cases it will overwrite the ID value in the entity with the calculated ID.
* @param {?} __0
* @param {?} __1
* @return {?}
*/
EntityState.prototype.add =
// ------------------- ACTION HANDLERS -------------------
/**
* The entities given by the payload will be added.
* For certain ID strategies this might fail, if it provides an existing ID.
* In all cases it will overwrite the ID value in the entity with the calculated ID.
* @param {?} __0
* @param {?} __1
* @return {?}
*/
function (_a, _b) {
var _this = this;
var getState = _a.getState, patchState = _a.patchState;
var payload = _b.payload;
/** @type {?} */
var updated = this._addOrReplace(getState(), payload, (
// for automated ID strategies this mostly shouldn't throw an UnableToGenerateIdError error
// for EntityIdGenerator it will throw an error if no ID is present
// for automated ID strategies this mostly shouldn't throw an UnableToGenerateIdError error
// for EntityIdGenerator it will throw an error if no ID is present
/**
* @param {?} p
* @param {?} state
* @return {?}
*/
function (p, state) { return _this.idGenerator.generateId(p, state); }));
patchState(__assign({}, updated, { lastUpdated: Date.now() }));
};
/**
* The entities given by the payload will be added.
* It first checks if the ID provided by each entity does exist.
* If it does the current entity will be replaced.
* In all cases it will overwrite the ID value in the entity with the calculated ID.
*/
/**
* The entities given by the payload will be added.
* It first checks if the ID provided by each entity does exist.
* If it does the current entity will be replaced.
* In all cases it will overwrite the ID value in the entity with the calculated ID.
* @param {?} __0
* @param {?} __1
* @return {?}
*/
EntityState.prototype.createOrReplace = /**
* The entities given by the payload will be added.
* It first checks if the ID provided by each entity does exist.
* If it does the current entity will be replaced.
* In all cases it will overwrite the ID value in the entity with the calculated ID.
* @param {?} __0
* @param {?} __1
* @return {?}
*/
function (_a, _b) {
var _this = this;
var getState = _a.getState, patchState = _a.patchState;
var payload = _b.payload;
/** @type {?} */
var updated = this._addOrReplace(getState(), payload, (/**
* @param {?} p
* @param {?} state
* @return {?}
*/
function (p, state) {
return _this.idGenerator.getPresentIdOrGenerate(p, state);
}));
patchState(__assign({}, updated, { lastUpdated: Date.now() }));
};
/**
* @param {?} __0
* @param {?} __1
* @return {?}
*/
EntityState.prototype.update = /**
* @param {?} __0
* @param {?} __1
* @return {?}
*/
function (_a, _b) {
var _this = this;
var getState = _a.getState, patchState = _a.patchState;
var payload = _b.payload;
/** @type {?} */
var entities = __assign({}, getState().entities);
// create copy
/** @type {?} */
var affected;
if (payload.id === null) {
affected = Object.values(entities);
}
else if (typeof payload.id === 'function') {
affected = Object.values(entities).filter((/**
* @param {?} e
* @return {?}
*/
function (e) { return ((/** @type {?} */ (payload.id)))(e); }));
}
else {
/** @type {?} */
var ids_1 = asArray(payload.id);
affected = Object.values(entities).filter((/**
* @param {?} e
* @return {?}
*/
function (e) { return ids_1.includes(_this.idOf(e)); }));
}
if (typeof payload.data === 'function') {
affected.forEach((/**
* @param {?} e
* @return {?}
*/
function (e) {
entities = _this._update(entities, ((/** @type {?} */ (payload.data)))(e), _this.idOf(e));
}));
}
else {
affected.forEach((/**
* @param {?} e
* @return {?}
*/
function (e) {
entities = _this._update(entities, (/** @type {?} */ (payload.data)), _this.idOf(e));
}));
}
patchState({ entities: entities, lastUpdated: Date.now() });
};
/**
* @param {?} __0
* @param {?} __1
* @return {?}
*/
EntityState.prototype.updateActive = /**
* @param {?} __0
* @param {?} __1
* @return {?}
*/
function (_a, _b) {
var getState = _a.getState, patchState = _a.patchState;
var payload = _b.payload;
/** @type {?} */
var state = getState();
var _c = mustGetActive(state), id = _c.id, active = _c.active;
var entities = state.entities;
if (typeof payload === 'function') {
patchState({
entities: __assign({}, this._update(entities, payload(active), id)),
lastUpdated: Date.now()
});
}
else {
patchState({
entities: __assign({}, this._update(entities, payload, id)),
lastUpdated: Date.now()
});
}
};
/**
* @param {?} __0
* @return {?}
*/
EntityState.prototype.removeActive = /**
* @param {?} __0
* @return {?}
*/
function (_a) {
var getState = _a.getState, patchState = _a.patchState;
var _b = getState(), entities = _b.entities, ids = _b.ids, active = _b.active;
delete entities[active];
patchState({
entities: __assign({}, entities),
ids: ids.filter((/**
* @param {?} id
* @return {?}
*/
function (id) { return id !== active; })),
active: undefined,
lastUpdated: Date.now()
});
};
/**
* @param {?} __0
* @param {?} __1
* @return {?}
*/
EntityState.prototype.remove = /**
* @param {?} __0
* @param {?} __1
* @return {?}
*/
function (_a, _b) {
var _this = this;
var getState = _a.getState, patchState = _a.patchState;
var payload = _b.payload;
var _c = getState(), entities = _c.entities, ids = _c.ids, active = _c.active;
if (payload === null) {
patchState({
entities: {},
ids: [],
active: undefined,
lastUpdated: Date.now()
});
}
else {
/** @type {?} */
var deleteIds_1 = typeof payload === 'function'
? Object.values(entities)
.filter((/**
* @param {?} e
* @return {?}
*/
function (e) { return payload(e); }))
.map((/**
* @param {?} e
* @return {?}
*/
function (e) { return _this.idOf(e); }))
: asArray(payload);
/** @type {?} */
var wasActive = deleteIds_1.includes(active);
deleteIds_1.forEach((/**
* @param {?} id
* @return {?}
*/
function (id) { return delete entities[id]; }));
patchState({
entities: __assign({}, entities),
ids: ids.filter((/**
* @param {?} id
* @return {?}
*/
function (id) { return !deleteIds_1.includes(id); })),
active: wasActive ? undefined : active,
lastUpdated: Date.now()
});
}
};
/**
* @param {?} __0
* @return {?}
*/
EntityState.prototype.reset = /**
* @param {?} __0
* @return {?}
*/
function (_a) {
var setState = _a.setState;
setState(defaultEntityState());
};
/**
* @param {?} __0
* @param {?} __1
* @return {?}
*/
EntityState.prototype.setLoading = /**
* @param {?} __0
* @param {?} __1
* @return {?}
*/
function (_a, _b) {
var patchState = _a.patchState;
var payload = _b.payload;
patchState({ loading: payload });
};
/**
* @param {?} __0
* @param {?} __1
* @return {?}
*/
EntityState.prototype.setActive = /**
* @param {?} __0
* @param {?} __1
* @return {?}
*/
function (_a, _b) {
var patchState = _a.patchState;
var payload = _b.payload;
patchState({ active: payload });
};
/**
* @param {?} __0
* @return {?}
*/
EntityState.prototype.clearActive = /**
* @param {?} __0
* @return {?}
*/
function (_a) {
var patchState = _a.patchState;
patchState({ active: undefined });
};
/**
* @param {?} __0
* @param {?} __1
* @return {?}
*/
EntityState.prototype.setError = /**
* @param {?} __0
* @param {?} __1
* @return {?}
*/
function (_a, _b) {
var patchState = _a.patchState;
var payload = _b.payload;
patchState({ error: payload });
};
/**
* @param {?} __0
* @param {?} __1
* @return {?}
*/
EntityState.prototype.goToPage = /**
* @param {?} __0
* @param {?} __1
* @return {?}
*/
function (_a, _b) {
var getState = _a.getState, patchState = _a.patchState;
var payload = _b.payload;
if ('page' in payload) {
patchState({ pageIndex: payload.page });
return;
}
else if (payload['first']) {
patchState({ pageIndex: 0 });
return;
}
var _c = getState(), pageSize = _c.pageSize, pageIndex = _c.pageIndex, ids = _c.ids;
/** @type {?} */
var totalSize = ids.length;
/** @type {?} */
var maxIndex = Math.floor(totalSize / pageSize);
if ('last' in payload) {
patchState({ pageIndex: maxIndex });
}
else {
/** @type {?} */
var step = payload['prev'] ? -1 : 1;
/** @type {?} */
var index = pageIndex + step;
index = wrapOrClamp(payload.wrap, index, 0, maxIndex);
patchState({ pageIndex: index });
}
};
/**
* @param {?} __0
* @param {?} __1
* @return {?}
*/
EntityState.prototype.setPageSize = /**
* @param {?} __0
* @param {?} __1
* @return {?}
*/
function (_a, _b) {
var patchState = _a.patchState;
var payload = _b.payload;
patchState({ pageSize: payload });
};
// ------------------- UTILITY -------------------
/**
* A utility function to update the given state with the given entities.
* It returns a state model with the new entities map and IDs.
* For each given entity an ID will be generated. The generated ID will overwrite the current value:
* <code>entity[this.idKey] = generatedId(entity, state);</code>
* If the ID wasn't present, it will be added to the state's IDs array.
* @param state The current state to act on
* @param payload One or multiple partial entities
* @param generateId A function to generate an ID for each given entity
*/
// ------------------- UTILITY -------------------
/**
* A utility function to update the given state with the given entities.
* It returns a state model with the new entities map and IDs.
* For each given entity an ID will be generated. The generated ID will overwrite the current value:
* <code>entity[this.idKey] = generatedId(entity, state);</code>
* If the ID wasn't present, it will be added to the state's IDs array.
* @private
* @param {?} state The current state to act on
* @param {?} payload One or multiple partial entities
* @param {?} generateId A function to generate an ID for each given entity
* @return {?}
*/
EntityState.prototype._addOrReplace =
// ------------------- UTILITY -------------------
/**
* A utility function to update the given state with the given entities.
* It returns a state model with the new entities map and IDs.
* For each given entity an ID will be generated. The generated ID will overwrite the current value:
* <code>entity[this.idKey] = generatedId(entity, state);</code>
* If the ID wasn't present, it will be added to the state's IDs array.
* @private
* @param {?} state The current state to act on
* @param {?} payload One or multiple partial entities
* @param {?} generateId A function to generate an ID for each given entity
* @return {?}
*/
function (state, payload, generateId) {
var _this = this;
var entities = state.entities, ids = state.ids;
asArray(payload).forEach((/**
* @param {?} entity
* @return {?}
*/
function (entity) {
/** @type {?} */
var id = generateId(entity, state);
entity[_this.idKey] = id;
entities[id] = entity;
if (!ids.includes(id)) {
ids.push(id);
}
}));
return {
entities: __assign({}, entities),
ids: __spread(ids)
};
};
/**
* A utility function to update the given entities map with the provided partial entity.
* After checking if an entity with the given ID is present, the #onUpdate method is called.
* @param entities The current entity map
* @param entity The partial entity to update with
* @param id The ID to find the current entity in the map
*/
/**
* A utility function to update the given entities map with the provided partial entity.
* After checking if an entity with the given ID is present, the #onUpdate method is called.
* @private
* @param {?} entities The current entity map
* @param {?} entity The partial entity to update with
* @param {?=} id The ID to find the current entity in the map
* @return {?}
*/
EntityState.prototype._update = /**
* A utility function to update the given entities map with the provided partial entity.
* After checking if an entity with the given ID is present, the #onUpdate method is called.
* @private
* @param {?} entities The current entity map
* @param {?} entity The partial entity to update with
* @param {?=} id The ID to find the current entity in the map
* @return {?}
*/
function (entities, entity, id) {
if (id === void 0) { id = this.idOf(entity); }
if (id === undefined) {
throw new UpdateFailedError(new InvalidIdError(id));
}
/** @type {?} */
var current = entities[id];
if (current === undefined) {
throw new UpdateFailedError(new NoSuchEntityError(id));
}
entities[id] = this.onUpdate(current, entity);
return entities;
};
/**
* @private
* @param {?} storeClass
* @param {?} actions
* @return {?}
*/
EntityState.prototype.setup = /**
* @private
* @param {?} storeClass
* @param {?} actions
* @return {?}
*/
function (storeClass, actions) {
var _this = this;
// validation if a matching action handler exists has moved to reflection-validation tests
actions.forEach((/**
* @param {?} fn
* @return {?}
*/
function (fn) {
/** @type {?} */
var actionName = "[" + _this.storePath + "] " + fn;
storeClass[NGXS_META_KEY].actions[actionName] = [
{
fn: fn,
options: {},
type: actionName
}
];
}));
};
/**
* Returns the id of the given entity, based on the defined idKey.
* This methods allows Partial entities and thus might return undefined.
* Other methods calling this one have to handle this case themselves.
* @param data a partial entity
*/
/**
* Returns the id of the given entity, based on the defined idKey.
* This methods allows Partial entities and thus might return undefined.
* Other methods calling this one have to handle this case themselves.
* @protected
* @param {?} data a partial entity
* @return {?}
*/
EntityState.prototype.idOf = /**
* Returns the id of the given entity, based on the defined idKey.
* This methods allows Partial entities and thus might return undefined.
* Other methods calling this one have to handle this case themselves.
* @protected
* @param {?} data a partial entity
* @return {?}
*/
function (data) {
return data[this.idKey];
};
return EntityState;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
var IdStrategy;
(function (IdStrategy) {
/**
* @abstract
* @template T
*/
var /**
* @abstract
* @template T
*/
IdGenerator = /** @class */ (function () {
function IdGenerator(idKey) {
this.idKey = idKey;
}
/**
* Checks if the given id is in the state's ID array
* @param id the ID to check
* @param state the current state
*/
/**
* Checks if the given id is in the state's ID array
* @param {?} id the ID to check
* @param {?} state the current state
* @return {?}
*/
IdGenerator.prototype.isIdInState = /**
* Checks if the given id is in the state's ID array
* @param {?} id the ID to check
* @param {?} state the current state
* @return {?}
*/
function (id, state) {
return state.ids.includes(id);
};
/**
* This function tries to get the present ID of the given entity with #getIdOf.
* If it's undefined the #generateId function will be used.
* @param entity The entity to get the ID from
* @param state The current state
* @see getIdOf
* @see generateId
*/
/**
* This function tries to get the present ID of the given entity with #getIdOf.
* If it's undefined the #generateId function will be used.
* @see getIdOf / generateId
* @param {?} entity The entity to get the ID from
* @param {?} state The current state
* @return {?}
*/
IdGenerator.prototype.getPresentIdOrGenerate = /**
* This function tries to get the present ID of the given entity with #getIdOf.
* If it's undefined the #generateId function will be used.
* @see getIdOf / generateId
* @param {?} entity The entity to get the ID from
* @param {?} state The current state
* @return {?}
*/
function (entity, state) {
/** @type {?} */
var presentId = this.getIdOf(entity);
return presentId === undefined ? this.generateId(entity, state) : presentId;
};
/**
* A wrapper for #getIdOf. If the function returns undefined an error will be thrown.
* @param entity The entity to get the ID from
* @see getIdOf
* @see InvalidIdOfError
*/
/**
* A wrapper for #getIdOf. If the function returns undefined an error will be thrown.
* @see getIdOf / InvalidIdOfError
* @param {?} entity The entity to get the ID from
* @return {?}
*/
IdGenerator.prototype.mustGetIdOf = /**
* A wrapper for #getIdOf. If the function returns undefined an error will be thrown.
* @see getIdOf / InvalidIdOfError
* @param {?} entity The entity to get the ID from
* @return {?}
*/
function (entity) {
/** @type {?} */
var id = this.getIdOf(entity);
if (id === undefined) {
throw new InvalidIdOfError();
}
return id;
};
/**
* Returns the ID for the given entity. Can return undefined.
* @param entity The entity to get the ID from
*/
/**
* Returns the ID for the given entity. Can return undefined.
* @param {?} entity The entity to get the ID from
* @return {?}
*/
IdGenerator.prototype.getIdOf = /**
* Returns the ID for the given entity. Can return undefined.
* @param {