@datorama/akita
Version:
State Management Tailored-Made for JS Applications
790 lines (775 loc) • 28.7 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/common/http'), require('rxjs'), require('rxjs/operators'), require('@angular/core'), require('@datorama/akita')) :
typeof define === 'function' && define.amd ? define('@datorama/akita/angular/playground/projects/ng-entity-service', ['exports', '@angular/common/http', 'rxjs', 'rxjs/operators', '@angular/core', '@datorama/akita'], factory) :
(factory((global.datorama = global.datorama || {}, global.datorama.akita = global.datorama.akita || {}, global.datorama.akita.angular = global.datorama.akita.angular || {}, global.datorama.akita.angular.playground = global.datorama.akita.angular.playground || {}, global.datorama.akita.angular.playground.projects = global.datorama.akita.angular.playground.projects || {}, global.datorama.akita.angular.playground.projects['ng-entity-service'] = {}),global.ng.common.http,global.rxjs,global.rxjs.operators,global.ng.core,global.datorama.akita));
}(this, (function (exports,http,rxjs,operators,i0,akita) { 'use strict';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b)
if (b.hasOwnProperty(p))
d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m)
return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
ar.push(r.value);
}
catch (error) {
e = { error: error };
}
finally {
try {
if (r && !r.done && (m = i["return"]))
m.call(i);
}
finally {
if (e)
throw e.error;
}
}
return ar;
}
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @enum {string} */
var HttpMethod = {
GET: 'GET',
POST: 'POST',
PUT: 'PUT',
PATCH: 'PATCH',
DELETE: 'DELETE',
};
/** @type {?} */
var ofType = ( /**
* @param {?} type
* @return {?}
*/function (type) {
return operators.filter(( /**
* @param {?} action
* @return {?}
*/function (action) { return action.type === type; }));
});
/** @type {?} */
var filterMethod = ( /**
* @param {?} method
* @return {?}
*/function (method) {
return operators.filter(( /**
* @param {?} action
* @return {?}
*/function (action) { return action.method === method; }));
});
/** @type {?} */
var filterStore = ( /**
* @param {?} name
* @return {?}
*/function (name) {
return operators.filter(( /**
* @param {?} action
* @return {?}
*/function (action) { return action.storeName === name; }));
});
var NgEntityServiceNotifier = /** @class */ (function () {
function NgEntityServiceNotifier() {
this.dispatcher = new rxjs.Subject();
this.action$ = this.dispatcher.asObservable();
}
/**
* @param {?} event
* @return {?}
*/
NgEntityServiceNotifier.prototype.dispatch = /**
* @param {?} event
* @return {?}
*/
function (event) {
this.dispatcher.next(event);
};
NgEntityServiceNotifier.decorators = [
{ type: i0.Injectable, args: [{ providedIn: 'root' },] }
];
/** @nocollapse */ NgEntityServiceNotifier.ngInjectableDef = i0.defineInjectable({ factory: function NgEntityServiceNotifier_Factory() { return new NgEntityServiceNotifier(); }, token: NgEntityServiceNotifier, providedIn: "root" });
return NgEntityServiceNotifier;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
var NgEntityServiceLoader = /** @class */ (function () {
function NgEntityServiceLoader() {
this.dispatcher = new rxjs.Subject();
this.loading$ = this.dispatcher.asObservable();
}
/**
* @param {?} event
* @return {?}
*/
NgEntityServiceLoader.prototype.dispatch = /**
* @param {?} event
* @return {?}
*/
function (event) {
this.dispatcher.next(event);
};
/**
* @param {?=} name
* @return {?}
*/
NgEntityServiceLoader.prototype.loadersFor = /**
* @param {?=} name
* @return {?}
*/
function (name) {
var _this = this;
/** @type {?} */
var filterStore$$1 = operators.filter(( /**
* @param {?} __0
* @return {?}
*/function (_a) {
var storeName = _a.storeName;
return (name ? storeName === name : true);
}));
/** @type {?} */
var filterMethod$$1 = ( /**
* @param {?} mthd
* @return {?}
*/function (mthd) {
return operators.filter(( /**
* @param {?} __0
* @return {?}
*/function (_a) {
var method = _a.method;
return akita.isFunction(mthd) ? mthd(method) : method === mthd;
}));
});
/** @type {?} */
var actionBased = ( /**
* @param {?} current
* @return {?}
*/function (current) {
return _this.loading$.pipe(filterStore$$1, filterMethod$$1(current), operators.map(( /**
* @param {?} action
* @return {?}
*/function (action) { return action.loading; })));
});
/** @type {?} */
var idBased = ( /**
* @param {?} id
* @param {?} mthd
* @return {?}
*/function (id, mthd) {
return _this.loading$.pipe(filterStore$$1, filterMethod$$1(mthd), operators.filter(( /**
* @param {?} action
* @return {?}
*/function (action) { return action.entityId === id; })), operators.map(( /**
* @param {?} action
* @return {?}
*/function (action) { return action.loading; })));
});
return {
get$: actionBased(HttpMethod.GET),
add$: actionBased(HttpMethod.POST),
update$: actionBased(( /**
* @param {?} method
* @return {?}
*/function (method) { return method === HttpMethod.PUT || method === HttpMethod.PATCH; })),
delete$: actionBased(HttpMethod.DELETE),
getEntity: ( /**
* @param {?} id
* @return {?}
*/function (id) { return idBased(id, HttpMethod.GET); }),
updateEntity: ( /**
* @param {?} id
* @return {?}
*/function (id) {
return idBased(id, ( /**
* @param {?} method
* @return {?}
*/function (method) { return method === HttpMethod.PUT || method === HttpMethod.PATCH; }));
}),
deleteEntity: ( /**
* @param {?} id
* @return {?}
*/function (id) { return idBased(id, HttpMethod.DELETE); })
};
};
NgEntityServiceLoader.decorators = [
{ type: i0.Injectable, args: [{ providedIn: 'root' },] }
];
/** @nocollapse */ NgEntityServiceLoader.ngInjectableDef = i0.defineInjectable({ factory: function NgEntityServiceLoader_Factory() { return new NgEntityServiceLoader(); }, token: NgEntityServiceLoader, providedIn: "root" });
return NgEntityServiceLoader;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @type {?} */
var NG_ENTITY_SERVICE_CONFIG = new i0.InjectionToken('NgEntityServiceGlobalConfig');
/** @type {?} */
var defaultConfig = {
httpMethods: {
GET: HttpMethod.GET,
POST: HttpMethod.POST,
PATCH: HttpMethod.PATCH,
PUT: HttpMethod.PUT,
DELETE: HttpMethod.DELETE
}
};
/**
* @param {?} target
* @param {...?} sources
* @return {?}
*/
function mergeDeep(target) {
var sources = [];
for (var _i = 1; _i < arguments.length; _i++) {
sources[_i - 1] = arguments[_i];
}
var _a, _b;
if (!sources.length)
return target;
/** @type {?} */
var source = sources.shift();
if (akita.isObject(target) && akita.isObject(source)) {
for (var key in source) {
if (akita.isObject(source[key])) {
if (!target[key])
Object.assign(target, (_a = {}, _a[key] = {}, _a));
mergeDeep(target[key], source[key]);
}
else {
Object.assign(target, (_b = {}, _b[key] = source[key], _b));
}
}
}
return mergeDeep.apply(void 0, __spread([target], sources));
}
/**
* @param {?=} config
* @return {?}
*/
function NgEntityServiceConfig(config) {
if (config === void 0) {
config = {};
}
return ( /**
* @param {?} constructor
* @return {?}
*/function (constructor) {
if (config.baseUrl) {
constructor['baseUrl'] = config.baseUrl;
}
if (config.resourceName) {
constructor['resourceName'] = config.resourceName;
}
});
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @param {?} idOrConfig
* @return {?}
*/
function isID(idOrConfig) {
return akita.isNumber(idOrConfig) || akita.isString(idOrConfig);
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @param {?} storeName
* @param {?} notifier
* @return {?}
*/
function successAction(storeName, notifier) {
return ( /**
* @param {?} __0
* @return {?}
*/function (_a) {
var payload = _a.payload, method = _a.method, successMsg = _a.successMsg;
notifier.dispatch({
type: 'success',
storeName: storeName,
payload: payload,
method: method,
successMsg: successMsg
});
});
}
/**
* @param {?} storeName
* @param {?} notifier
* @return {?}
*/
function errorAction(storeName, notifier) {
return ( /**
* @param {?} __0
* @return {?}
*/function (_a) {
var payload = _a.payload, method = _a.method, errorMsg = _a.errorMsg;
notifier.dispatch({
type: 'error',
storeName: storeName,
payload: payload,
method: method,
errorMsg: errorMsg
});
});
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @type {?} */
var mapResponse = ( /**
* @param {?} config
* @return {?}
*/function (config) {
return operators.map(( /**
* @param {?} res
* @return {?}
*/function (res) { return ((config || {}).mapResponseFn ? config.mapResponseFn(res) : res); }));
});
/**
* @template S
*/
var /**
* @template S
*/ NgEntityService = /** @class */ (function (_super) {
__extends(NgEntityService, _super);
function NgEntityService(store, config) {
if (config === void 0) {
config = {};
}
var _this = _super.call(this) || this;
_this.store = store;
_this.config = config;
_this.globalConfig = {};
_this.http = i0.inject(http.HttpClient);
_this.loader = i0.inject(NgEntityServiceLoader);
_this.notifier = i0.inject(NgEntityServiceNotifier);
_this.globalConfig = i0.inject(NG_ENTITY_SERVICE_CONFIG);
_this.mergedConfig = mergeDeep(defaultConfig, _this.globalConfig, config);
_this.dispatchSuccess = successAction(_this.store.storeName, _this.notifier);
_this.dispatchError = errorAction(_this.store.storeName, _this.notifier);
return _this;
}
Object.defineProperty(NgEntityService.prototype, "api", {
get: /**
* @return {?}
*/ function () {
return (this.baseUrl || this.getConfigValue('baseUrl')) + "/" + this.resourceName;
},
enumerable: true,
configurable: true
});
Object.defineProperty(NgEntityService.prototype, "resourceName", {
get: /**
* @return {?}
*/ function () {
return this.getConfigValue('resourceName') || this.store.storeName;
},
enumerable: true,
configurable: true
});
/**
* @param {?} api
* @return {?}
*/
NgEntityService.prototype.setBaseUrl = /**
* @param {?} api
* @return {?}
*/
function (api) {
this.baseUrl = api;
};
/**
* @template T
* @param {?=} idOrConfig
* @param {?=} config
* @return {?}
*/
NgEntityService.prototype.get = /**
* @template T
* @param {?=} idOrConfig
* @param {?=} config
* @return {?}
*/
function (idOrConfig, config) {
var _this = this;
/** @type {?} */
var url;
/** @type {?} */
var isSingle = isID(idOrConfig);
/** @type {?} */
var _config = (isSingle ? config : idOrConfig) || {};
/** @type {?} */
var method = this.getHttpMethod(HttpMethod.GET);
if (_config.url) {
url = _config.url;
}
else {
url = isSingle ? this.api + "/" + idOrConfig : this.api;
}
this.loader.dispatch({
method: method,
loading: true,
entityId: isSingle ? idOrConfig : null,
storeName: this.store.storeName
});
return ( /** @type {?} */(this.http[method.toLowerCase()](url, _config).pipe(mapResponse(_config), operators.tap(( /**
* @param {?} data
* @return {?}
*/function (data) {
if (isSingle) {
_this.store.upsert(( /** @type {?} */(idOrConfig)), data);
}
else {
_config.append ? _this.store.add(data) : _this.store.set(data);
}
_this.dispatchSuccess({
method: method,
payload: data,
successMsg: _config.successMsg
});
})), operators.catchError(( /**
* @param {?} error
* @return {?}
*/function (error) { return _this.handleError(method, error, _config.errorMsg); })), operators.finalize(( /**
* @return {?}
*/function () {
_this.loader.dispatch({
method: method,
loading: false,
storeName: _this.store.storeName
});
})))));
};
/**
*
* Add a new entity - Creates a POST request
*
* service.add(entity)
* service.add(entity, config)
*
*/
/**
*
* Add a new entity - Creates a POST request
*
* service.add(entity)
* service.add(entity, config)
*
* @template T
* @param {?} entity
* @param {?=} config
* @return {?}
*/
NgEntityService.prototype.add = /**
*
* Add a new entity - Creates a POST request
*
* service.add(entity)
* service.add(entity, config)
*
* @template T
* @param {?} entity
* @param {?=} config
* @return {?}
*/
function (entity, config) {
var _this = this;
/** @type {?} */
var method = this.getHttpMethod(HttpMethod.POST);
this.loader.dispatch({
method: method,
loading: true,
storeName: this.store.storeName
});
return ( /** @type {?} */(this.http[method.toLowerCase()](this.resolveUrl(config), entity, config).pipe(mapResponse(config), operators.tap(( /**
* @param {?} entity
* @return {?}
*/function (entity) {
_this.store.add(entity, config);
_this.dispatchSuccess({
method: method,
payload: entity,
successMsg: config && config.successMsg
});
})), operators.catchError(( /**
* @param {?} error
* @return {?}
*/function (error) { return _this.handleError(method, error, config && config.errorMsg); })), operators.finalize(( /**
* @return {?}
*/function () {
_this.loader.dispatch({
method: method,
loading: false,
storeName: _this.store.storeName
});
})))));
};
/**
*
* Update an entity - Creates a PUT/PATCH request
*
* service.update(id, entity)
* service.update(id, entity, config)
*
*/
/**
*
* Update an entity - Creates a PUT/PATCH request
*
* service.update(id, entity)
* service.update(id, entity, config)
*
* @template T
* @param {?} id
* @param {?} entity
* @param {?=} config
* @return {?}
*/
NgEntityService.prototype.update = /**
*
* Update an entity - Creates a PUT/PATCH request
*
* service.update(id, entity)
* service.update(id, entity, config)
*
* @template T
* @param {?} id
* @param {?} entity
* @param {?=} config
* @return {?}
*/
function (id, entity, config) {
var _this = this;
/** @type {?} */
var method = config && config.method ? config.method : this.getHttpMethod(HttpMethod.PUT);
this.loader.dispatch({
method: method,
loading: true,
entityId: id,
storeName: this.store.storeName
});
return ( /** @type {?} */(this.http[method.toLocaleLowerCase()](this.resolveUrl(config, id), entity, config).pipe(mapResponse(config), operators.tap(( /**
* @param {?} entity
* @return {?}
*/function (entity) {
_this.store.update(id, ( /** @type {?} */(entity)));
_this.dispatchSuccess({
method: method,
payload: entity,
successMsg: config && config.successMsg
});
})), operators.catchError(( /**
* @param {?} error
* @return {?}
*/function (error) { return _this.handleError(method, error, config && config.errorMsg); })), operators.finalize(( /**
* @return {?}
*/function () {
_this.loader.dispatch({
method: method,
loading: false,
entityId: id,
storeName: _this.store.storeName
});
})))));
};
/**
*
* Delete an entity - Creates a DELETE request
*
* service.delete(id)
* service.delete(id, config)
*
*/
/**
*
* Delete an entity - Creates a DELETE request
*
* service.delete(id)
* service.delete(id, config)
*
* @template T
* @param {?} id
* @param {?=} config
* @return {?}
*/
NgEntityService.prototype.delete = /**
*
* Delete an entity - Creates a DELETE request
*
* service.delete(id)
* service.delete(id, config)
*
* @template T
* @param {?} id
* @param {?=} config
* @return {?}
*/
function (id, config) {
var _this = this;
/** @type {?} */
var method = this.getHttpMethod(HttpMethod.DELETE);
this.loader.dispatch({
method: method,
loading: true,
entityId: id,
storeName: this.store.storeName
});
return ( /** @type {?} */(this.http[method.toLowerCase()](this.resolveUrl(config, id), config).pipe(mapResponse(config), operators.tap(( /**
* @param {?} res
* @return {?}
*/function (res) {
_this.store.remove(id);
_this.dispatchSuccess({
method: method,
payload: res,
successMsg: config && config.successMsg
});
})), operators.catchError(( /**
* @param {?} error
* @return {?}
*/function (error) { return _this.handleError(method, error, config && config.errorMsg); })), operators.finalize(( /**
* @return {?}
*/function () {
_this.loader.dispatch({
method: method,
loading: false,
entityId: id,
storeName: _this.store.storeName
});
})))));
};
/**
* @private
* @param {?} type
* @return {?}
*/
NgEntityService.prototype.getHttpMethod = /**
* @private
* @param {?} type
* @return {?}
*/
function (type) {
return this.mergedConfig.httpMethods[type];
};
/**
* @private
* @param {?} key
* @return {?}
*/
NgEntityService.prototype.getConfigValue = /**
* @private
* @param {?} key
* @return {?}
*/
function (key) {
return this.constructor[key] || this.mergedConfig[key];
};
/**
* @private
* @param {?} config
* @param {?=} id
* @return {?}
*/
NgEntityService.prototype.resolveUrl = /**
* @private
* @param {?} config
* @param {?=} id
* @return {?}
*/
function (config, id) {
/** @type {?} */
var customUrl = (config || {}).url;
if (akita.isDefined(id)) {
return customUrl || this.api + "/" + id;
}
return customUrl || this.api;
};
/**
* @private
* @param {?} method
* @param {?} error
* @param {?} errorMsg
* @return {?}
*/
NgEntityService.prototype.handleError = /**
* @private
* @param {?} method
* @param {?} error
* @param {?} errorMsg
* @return {?}
*/
function (method, error, errorMsg) {
this.dispatchError({
method: method,
errorMsg: errorMsg,
payload: error
});
return rxjs.throwError(error);
};
return NgEntityService;
}(akita.EntityService));
/**
* @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
*/
exports.mapResponse = mapResponse;
exports.NgEntityService = NgEntityService;
exports.mergeDeep = mergeDeep;
exports.NgEntityServiceConfig = NgEntityServiceConfig;
exports.NG_ENTITY_SERVICE_CONFIG = NG_ENTITY_SERVICE_CONFIG;
exports.defaultConfig = defaultConfig;
exports.HttpMethod = HttpMethod;
exports.ofType = ofType;
exports.filterMethod = filterMethod;
exports.filterStore = filterStore;
exports.NgEntityServiceNotifier = NgEntityServiceNotifier;
exports.isID = isID;
exports.NgEntityServiceLoader = NgEntityServiceLoader;
exports.successAction = successAction;
exports.errorAction = errorAction;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=datorama-akita-angular-playground-projects-ng-entity-service.umd.js.map