resource-toolkit
Version:
Async and RESTful resource management tool.
953 lines (941 loc) • 50.6 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = global || self, factory(global['resource-toolkit'] = {}));
}(this, (function (exports) { '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 __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __awaiter(thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
}
var EMPTY_INITIAL_STATE = Object.freeze({
items: [],
relatedsTo: {},
isCreating: false,
isReadingBlindly: false,
isReadingAll: false,
reading: [],
updating: [],
deleting: [],
isLoading: false,
finishingLogs: [],
currentMessage: null,
meta: {},
});
var ResourceToolkitError = /** @class */ (function (_super) {
__extends(ResourceToolkitError, _super);
function ResourceToolkitError() {
return _super !== null && _super.apply(this, arguments) || this;
}
return ResourceToolkitError;
}(Error));
function makeDefaultMessageText(relating, operation, error) {
var isError = error instanceof Error || error;
var attachmentForMany = Array.isArray(relating) ? " Related to " + relating.length + " items." : '';
switch (operation) {
case 'CREATE':
return (isError ? 'Failed to create.' : 'Successfully created.') + attachmentForMany;
case 'READ':
return (isError ? 'Failed to fetch data.' : 'Successfully fetched data.') + attachmentForMany;
case 'UPDATE':
return (isError ? 'Failed to update.' : 'Successfully updated.');
case 'DELETE':
return (isError ? 'Failed to delete.' : 'Successfully deleted.');
case 'RELATED':
case 'RELATED_CREATED':
case 'RELATED_READ':
case 'RELATED_UPDATED':
case 'RELATED_DELETED':
return (isError ? 'Failed operation on related data.' : 'Successful operation on related data.');
default:
return isError
? 'Unknown and unexpected error response.'
: 'Success, but with unknown and unexpected response.';
}
}
function handleErrorFn(namespace, logLibError) {
return function handleError(error) {
if (error instanceof ResourceToolkitError) {
logLibError("[" + namespace + "]", error);
}
};
}
function blockNonIdentifying(identifying) {
if (!Array.isArray(identifying)) {
blockNonIdentifier(identifying);
return;
}
if (identifying.length === 0) {
throw new ResourceToolkitError('Expected ids with string or numbers, but got the array empty.');
}
identifying.forEach(function (identifier) {
var idType = typeof identifier;
if (!validIdentifierTypes.includes(idType)) {
throw new ResourceToolkitError("Expected ids as strings or numbers, but got an array with " + idType + ".");
}
});
}
function blockNonIdentifier(identifier) {
var idType = typeof identifier;
if (!validIdentifierTypes.includes(idType)) {
throw new ResourceToolkitError("Expected unique id to be string or number, but got " + idType + ".");
}
}
function blockNonDataWithMeta(payload) {
if (!isObjectInstance(payload) || isArrayInstance(payload)) {
throw new ResourceToolkitError("Expected Object instance as payload, but got something else of type " + typeof payload + ".");
}
var data = payload.data;
if (!isObjectInstance(data) || !isArrayInstance(data)) {
throw new ResourceToolkitError("Expected Array or Object instance as data, but got something else of type " + typeof data + ".");
}
var meta = payload.meta;
if (!isObjectInstance(meta)) {
throw new ResourceToolkitError("Expected Object instance as meta, but got something else of type " + typeof meta + ".");
}
}
function blockNonEntitiesFn(idKey) {
return function blockNonEntities(items) {
if (!isArrayInstance(items)) {
throw new ResourceToolkitError("Expected Array instance as gateway return, but got something else of type " + typeof items + ".");
}
items.forEach(function (item, index) {
if (!isObjectInstance(item) || isArrayInstance(item)) {
throw new ResourceToolkitError("Expected single Object instances in gateway items, but got something else of type " + typeof item + " at index " + index + ".");
}
if (!item[idKey]) {
throw new ResourceToolkitError("Expected truthy \"entityId\" in gateway items, but got something else of type " + typeof item[idKey] + " at index " + index + ".");
}
if (!['string', 'number'].includes(typeof item[idKey])) {
throw new ResourceToolkitError("Expected string or number for \"" + idKey + "\" in gateway items, but got something else of type " + typeof item[idKey] + " at index " + index + ".");
}
});
};
}
function blockNonEntityFn(idKey) {
return function blockNonEntity(item) {
if (isArrayInstance(item)) {
throw new ResourceToolkitError('Expected single Object instance as gateway return, but got an Array.');
}
if (!isObjectInstance(item)) {
throw new ResourceToolkitError("Expected Object instance as gateway return, but got something else of type " + typeof item + ".");
}
if (!item[idKey]) {
throw new ResourceToolkitError("Expected truthy \"" + idKey + "\" in gateway return, but got something else of type " + typeof item[idKey] + ".");
}
if (!['string', 'number'].includes(typeof item[idKey])) {
throw new ResourceToolkitError("Expected string or number for \"" + idKey + "\" in gateway return, but got something else of type " + typeof item[idKey] + ".");
}
};
}
function minimalDelayedHOC(func, threshold) {
if (threshold === void 0) { threshold = 1000; }
var initialTime = Date.now();
var thresholdTime = initialTime + threshold;
return function minimalDelayedDo() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return new Promise(function (resolve, reject) {
var pendingTime = thresholdTime - Date.now();
if (pendingTime > 0) {
global.setTimeout(function () {
try {
resolve(func.apply(void 0, args));
}
catch (error) {
reject(error);
}
}, pendingTime);
}
else {
try {
resolve(func.apply(void 0, args));
}
catch (error) {
reject(error);
}
}
});
};
}
var isObjectInstance = function (x) { return x instanceof Object; };
var isArrayInstance = function (x) { return Array.isArray(x); };
var validIdentifierTypes = ['string', 'number'];
function makeReducerAssets(params) {
var _this = this;
if (!isObjectInstance(params) || isArrayInstance(params)) {
throw new ResourceToolkitError("Expected params object on assets factory, got something else of type " + typeof params + ".");
}
var name = params.name, idKey = params.idKey, gateway = params.gateway, _a = params.relatedKeys, relatedKeys = _a === void 0 ? {} : _a, _b = params.expectAllMeta, expectAllMeta = _b === void 0 ? false : _b, _c = params.makeMessageText, makeMessageText = _c === void 0 ? makeDefaultMessageText : _c, _d = params.logLibError, logLibError = _d === void 0 ? console.error : _d;
if (!name || typeof name !== 'string') {
throw new ResourceToolkitError("Expected truthy \"name\" string on assets factory, got something else of type " + typeof name + ".");
}
if (!idKey || typeof idKey !== 'string') {
throw new ResourceToolkitError("Expected truthy \"idKey\" string on assets factory, got something else of type " + typeof idKey + ".");
}
var handleError = handleErrorFn(name, logLibError);
var actionType = "RESOURCE_TOOLKIT__" + name;
var makeAction = function (payload) {
return {
type: actionType,
payload: payload,
};
};
var plainActions = {
setCreating: function () { return makeAction({
operation: 'CREATE',
step: 'DOING',
}); },
setReading: function (identifying) {
if (identifying === void 0) { identifying = null; }
return makeAction({
operation: 'READ',
step: 'DOING',
identifying: identifying,
});
},
setUpdating: function (identifying) { return makeAction({
operation: 'UPDATE',
step: 'DOING',
identifying: identifying,
}); },
setDeleting: function (identifying) { return makeAction({
operation: 'DELETE',
step: 'DOING',
identifying: identifying,
}); },
setRelatedLoading: function (ownerIdentifier, relationshipKey) { return makeAction({
operation: 'RELATED',
step: 'DOING',
identifying: ownerIdentifier,
relationshipKey: relationshipKey,
}); },
setRead: function (identifying, content) { return makeAction({
operation: 'READ',
step: 'SUCCESS',
identifying: identifying,
content: content,
}); },
setUpdated: function (identifying, content) { return makeAction({
operation: 'UPDATE',
step: 'SUCCESS',
identifying: identifying,
content: content,
}); },
setCreated: function (content) { return makeAction({
operation: 'CREATE',
step: 'SUCCESS',
content: content,
}); },
setDeleted: function (identifying) { return makeAction({
operation: 'DELETE',
step: 'SUCCESS',
identifying: identifying,
}); },
setRelatedCreated: function (ownerIdentifier, relationshipKey, content) { return makeAction({
operation: 'RELATED_CREATED',
step: 'SUCCESS',
identifying: ownerIdentifier,
relationshipKey: relationshipKey,
content: content,
}); },
setRelatedRead: function (ownerIdentifier, relationshipKey, content) { return makeAction({
operation: 'RELATED_READ',
step: 'SUCCESS',
identifying: ownerIdentifier,
relationshipKey: relationshipKey,
content: content,
}); },
setRelatedUpdated: function (ownerIdentifier, relationshipKey, content) { return makeAction({
operation: 'RELATED_UPDATED',
step: 'SUCCESS',
identifying: ownerIdentifier,
relationshipKey: relationshipKey,
content: content,
}); },
setRelatedDeleted: function (ownerIdentifier, relationshipKey, content) { return makeAction({
operation: 'RELATED_DELETED',
step: 'SUCCESS',
identifying: ownerIdentifier,
relationshipKey: relationshipKey,
content: content,
}); },
setCreateError: function (causedByError) { return makeAction({
operation: 'CREATE',
step: 'ERROR',
content: causedByError,
}); },
setReadError: function (identifying, causedByError) { return makeAction({
operation: 'READ',
step: 'ERROR',
content: causedByError,
identifying: identifying,
}); },
setUpdateError: function (identifying, causedByError) { return makeAction({
operation: 'UPDATE',
step: 'ERROR',
content: causedByError,
identifying: identifying,
}); },
setDeleteError: function (identifying, causedByError) { return makeAction({
operation: 'DELETE',
step: 'ERROR',
content: causedByError,
identifying: identifying,
}); },
setRelatedError: function (ownerIdentifier, relationshipKey, causedByError) { return makeAction({
operation: 'RELATED',
step: 'ERROR',
content: causedByError,
identifying: ownerIdentifier,
relationshipKey: relationshipKey,
}); },
setIsReadingAll: function (isReadingAll) { return makeAction({
operation: isReadingAll ? 'SET_READING_ALL' : 'SET_NOT_READING_ALL',
step: 'SUCCESS',
}); },
setMeta: function (meta) { return makeAction({
operation: 'SET_META',
step: 'SUCCESS',
content: meta,
}); },
clearItems: function () { return makeAction({
operation: 'CLEAR_ITEMS',
step: 'SUCCESS',
}); },
clearCurrentMessage: function () { return makeAction({
operation: 'CLEAR_CURRENT_MESSAGE',
step: 'SUCCESS',
}); },
};
var blockNonEntity = blockNonEntityFn(idKey);
var blockNonEntities = blockNonEntitiesFn(idKey);
var actionThunks = {
create: function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return function (dispatch) { return __awaiter(_this, void 0, void 0, function () {
var gracefullyDispatch, content, error_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
dispatch(plainActions.setCreating());
gracefullyDispatch = minimalDelayedHOC(dispatch);
_a.label = 1;
case 1:
_a.trys.push([1, 4, , 6]);
return [4 /*yield*/, gateway.create.apply(gateway, args)];
case 2:
content = _a.sent();
blockNonEntity(content);
return [4 /*yield*/, gracefullyDispatch(plainActions.setCreated(content))];
case 3:
_a.sent();
return [3 /*break*/, 6];
case 4:
error_1 = _a.sent();
return [4 /*yield*/, gracefullyDispatch(plainActions.setCreateError(error_1))];
case 5:
_a.sent();
handleError(error_1);
return [3 /*break*/, 6];
case 6: return [2 /*return*/];
}
});
}); };
},
readOne: function (identifier) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
return function (dispatch) { return __awaiter(_this, void 0, void 0, function () {
var gracefullyDispatch, content, error_2;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
blockNonIdentifier(identifier);
dispatch(plainActions.setReading(identifier));
gracefullyDispatch = minimalDelayedHOC(dispatch);
_a.label = 1;
case 1:
_a.trys.push([1, 4, , 6]);
return [4 /*yield*/, gateway.fetchOne.apply(gateway, __spreadArrays([identifier], args))];
case 2:
content = _a.sent();
blockNonEntity(content);
return [4 /*yield*/, gracefullyDispatch(plainActions.setRead(identifier, content))];
case 3:
_a.sent();
return [3 /*break*/, 6];
case 4:
error_2 = _a.sent();
return [4 /*yield*/, gracefullyDispatch(plainActions.setReadError(identifier, error_2))];
case 5:
_a.sent();
return [3 /*break*/, 6];
case 6: return [2 /*return*/];
}
});
}); };
},
readMany: function (identifers) {
if (identifers === void 0) { identifers = null; }
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
return function (dispatch) { return __awaiter(_this, void 0, void 0, function () {
var gracefullyDispatch, content, error_3;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (identifers !== null) {
blockNonIdentifying(identifers);
}
dispatch(plainActions.setReading(identifers));
gracefullyDispatch = minimalDelayedHOC(dispatch);
_a.label = 1;
case 1:
_a.trys.push([1, 4, , 6]);
return [4 /*yield*/, gateway.fetchMany.apply(gateway, __spreadArrays([identifers], args))];
case 2:
content = _a.sent();
blockNonEntities(content);
return [4 /*yield*/, gracefullyDispatch(plainActions.setRead(identifers, content))];
case 3:
_a.sent();
return [3 /*break*/, 6];
case 4:
error_3 = _a.sent();
return [4 /*yield*/, gracefullyDispatch(plainActions.setReadError(identifers, error_3))];
case 5:
_a.sent();
handleError(error_3);
return [3 /*break*/, 6];
case 6: return [2 /*return*/];
}
});
}); };
},
readAll: function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return function (dispatch) { return __awaiter(_this, void 0, void 0, function () {
var gracefullyDispatchError, gracefullyDispatchSuccess, payload, error_4;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
dispatch(plainActions.setReading());
dispatch(plainActions.setIsReadingAll(true));
gracefullyDispatchError = minimalDelayedHOC(function (error) {
dispatch(plainActions.setReadError(null, error));
});
_a.label = 1;
case 1:
_a.trys.push([1, 4, 6, 7]);
gracefullyDispatchSuccess = minimalDelayedHOC(function (payload) {
if (expectAllMeta) {
blockNonDataWithMeta(payload);
dispatch(plainActions.clearItems());
var _a = payload, data = _a.data, meta = _a.meta;
blockNonEntities(data);
dispatch(plainActions.setMeta(meta));
dispatch(plainActions.setRead(null, data));
}
else {
blockNonEntities(payload);
dispatch(plainActions.clearItems());
dispatch(plainActions.setRead(null, payload));
}
});
return [4 /*yield*/, gateway.fetchMany.apply(gateway, __spreadArrays([null], args))];
case 2:
payload = _a.sent();
return [4 /*yield*/, gracefullyDispatchSuccess(payload)];
case 3:
_a.sent();
return [3 /*break*/, 7];
case 4:
error_4 = _a.sent();
return [4 /*yield*/, gracefullyDispatchError(error_4)];
case 5:
_a.sent();
handleError(error_4);
return [3 /*break*/, 7];
case 6:
dispatch(plainActions.setIsReadingAll(false));
return [7 /*endfinally*/];
case 7: return [2 /*return*/];
}
});
}); };
},
update: function (identifier) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
return function (dispatch) { return __awaiter(_this, void 0, void 0, function () {
var gracefullyDispatch, content, error_5;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
blockNonIdentifier(identifier);
dispatch(plainActions.setUpdating(identifier));
gracefullyDispatch = minimalDelayedHOC(dispatch);
_a.label = 1;
case 1:
_a.trys.push([1, 4, , 6]);
return [4 /*yield*/, gateway.update.apply(gateway, __spreadArrays([identifier], args))];
case 2:
content = _a.sent();
blockNonEntity(content);
return [4 /*yield*/, gracefullyDispatch(plainActions.setUpdated(identifier, content))];
case 3:
_a.sent();
return [3 /*break*/, 6];
case 4:
error_5 = _a.sent();
return [4 /*yield*/, gracefullyDispatch(plainActions.setUpdateError(identifier, error_5))];
case 5:
_a.sent();
handleError(error_5);
return [3 /*break*/, 6];
case 6: return [2 /*return*/];
}
});
}); };
},
delete: function (identifier) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
return function (dispatch) { return __awaiter(_this, void 0, void 0, function () {
var gracefullyDispatch, error_6;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
blockNonIdentifier(identifier);
dispatch(plainActions.setDeleting(identifier));
gracefullyDispatch = minimalDelayedHOC(dispatch);
_a.label = 1;
case 1:
_a.trys.push([1, 4, , 6]);
return [4 /*yield*/, gateway.delete.apply(gateway, __spreadArrays([identifier], args))];
case 2:
_a.sent();
return [4 /*yield*/, gracefullyDispatch(plainActions.setDeleted(identifier))];
case 3:
_a.sent();
return [3 /*break*/, 6];
case 4:
error_6 = _a.sent();
return [4 /*yield*/, gracefullyDispatch(plainActions.setDeleteError(identifier, error_6))];
case 5:
_a.sent();
handleError(error_6);
return [3 /*break*/, 6];
case 6: return [2 /*return*/];
}
});
}); };
},
readRelated: function (ownerIdentifier, relationshipKey) {
var args = [];
for (var _i = 2; _i < arguments.length; _i++) {
args[_i - 2] = arguments[_i];
}
return function (dispatch) { return __awaiter(_this, void 0, void 0, function () {
var gracefullyDispatch, content, error_7;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
blockNonIdentifier(ownerIdentifier);
dispatch(plainActions.setRelatedLoading(ownerIdentifier, relationshipKey));
gracefullyDispatch = minimalDelayedHOC(dispatch);
_a.label = 1;
case 1:
_a.trys.push([1, 4, , 6]);
return [4 /*yield*/, gateway.fetchRelated.apply(gateway, __spreadArrays([ownerIdentifier, relationshipKey], args))];
case 2:
content = _a.sent();
return [4 /*yield*/, gracefullyDispatch(plainActions.setRelatedRead(ownerIdentifier, relationshipKey, content))];
case 3:
_a.sent();
return [3 /*break*/, 6];
case 4:
error_7 = _a.sent();
return [4 /*yield*/, gracefullyDispatch(plainActions.setRelatedError(ownerIdentifier, relationshipKey, error_7))];
case 5:
_a.sent();
handleError(error_7);
return [3 /*break*/, 6];
case 6: return [2 /*return*/];
}
});
}); };
},
createRelated: function (ownerIdentifier, relationshipKey) {
var args = [];
for (var _i = 2; _i < arguments.length; _i++) {
args[_i - 2] = arguments[_i];
}
return function (dispatch) { return __awaiter(_this, void 0, void 0, function () {
var gracefullyDispatch, content, error_8;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
blockNonIdentifier(ownerIdentifier);
dispatch(plainActions.setRelatedLoading(ownerIdentifier, relationshipKey));
gracefullyDispatch = minimalDelayedHOC(dispatch);
_a.label = 1;
case 1:
_a.trys.push([1, 4, , 6]);
return [4 /*yield*/, gateway.createRelated.apply(gateway, __spreadArrays([ownerIdentifier, relationshipKey], args))];
case 2:
content = _a.sent();
return [4 /*yield*/, gracefullyDispatch(plainActions.setRelatedCreated(ownerIdentifier, relationshipKey, content))];
case 3:
_a.sent();
return [3 /*break*/, 6];
case 4:
error_8 = _a.sent();
return [4 /*yield*/, gracefullyDispatch(plainActions.setRelatedError(ownerIdentifier, relationshipKey, error_8))];
case 5:
_a.sent();
handleError(error_8);
return [3 /*break*/, 6];
case 6: return [2 /*return*/];
}
});
}); };
},
updateRelated: function (ownerIdentifier, relationshipKey) {
var args = [];
for (var _i = 2; _i < arguments.length; _i++) {
args[_i - 2] = arguments[_i];
}
return function (dispatch) { return __awaiter(_this, void 0, void 0, function () {
var gracefullyDispatch, content, error_9;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
blockNonIdentifier(ownerIdentifier);
dispatch(plainActions.setRelatedLoading(ownerIdentifier, relationshipKey));
gracefullyDispatch = minimalDelayedHOC(dispatch);
_a.label = 1;
case 1:
_a.trys.push([1, 4, , 6]);
return [4 /*yield*/, gateway.updateRelated.apply(gateway, __spreadArrays([ownerIdentifier, relationshipKey], args))];
case 2:
content = _a.sent();
return [4 /*yield*/, gracefullyDispatch(plainActions.setRelatedUpdated(ownerIdentifier, relationshipKey, content))];
case 3:
_a.sent();
return [3 /*break*/, 6];
case 4:
error_9 = _a.sent();
return [4 /*yield*/, gracefullyDispatch(plainActions.setRelatedError(ownerIdentifier, relationshipKey, error_9))];
case 5:
_a.sent();
handleError(error_9);
return [3 /*break*/, 6];
case 6: return [2 /*return*/];
}
});
}); };
},
deleteRelated: function (ownerIdentifier, relationshipKey) {
var args = [];
for (var _i = 2; _i < arguments.length; _i++) {
args[_i - 2] = arguments[_i];
}
return function (dispatch) { return __awaiter(_this, void 0, void 0, function () {
var gracefullyDispatch, content, error_10;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
blockNonIdentifier(ownerIdentifier);
dispatch(plainActions.setRelatedLoading(ownerIdentifier, relationshipKey));
gracefullyDispatch = minimalDelayedHOC(dispatch);
_a.label = 1;
case 1:
_a.trys.push([1, 4, , 6]);
return [4 /*yield*/, gateway.deleteRelated.apply(gateway, __spreadArrays([ownerIdentifier, relationshipKey], args))];
case 2:
content = _a.sent();
return [4 /*yield*/, gracefullyDispatch(plainActions.setRelatedDeleted(ownerIdentifier, relationshipKey, content))];
case 3:
_a.sent();
return [3 /*break*/, 6];
case 4:
error_10 = _a.sent();
return [4 /*yield*/, gracefullyDispatch(plainActions.setRelatedError(ownerIdentifier, relationshipKey, error_10))];
case 5:
_a.sent();
handleError(error_10);
return [3 /*break*/, 6];
case 6: return [2 /*return*/];
}
});
}); };
},
};
var initialState = EMPTY_INITIAL_STATE;
var reducer = function (state, action) {
if (state === void 0) { state = initialState; }
if (!action || action.type !== actionType) {
return state;
}
var payload = action.payload;
var operation = payload.operation, step = payload.step, identifying = payload.identifying, content = payload.content, relationshipKey = payload.relationshipKey;
var isLoading = step === 'DOING';
var isSuccess = step === 'SUCCESS';
var isError = step === 'ERROR';
var isFinished = isSuccess || isError;
var updating = __assign({}, state);
if (operation === 'CREATE') {
if (isLoading) {
updating.isCreating = true;
}
if (isSuccess) {
if (Array.isArray(content)) {
updating.items = __spreadArrays(state.items, content);
}
else if (content) {
updating.items = __spreadArrays(state.items, [content]);
}
}
if (isFinished) {
updating.isCreating = false;
}
}
if (operation === 'READ') {
if (isLoading) {
if (Array.isArray(identifying)) {
updating.reading = __spreadArrays(state.reading, identifying);
}
else if (identifying) {
updating.reading = __spreadArrays(state.reading, [identifying]);
}
else {
updating.isReadingBlindly = true;
}
}
if (isSuccess) {
var items = Array.isArray(content) ? content : [content];
updating.items = __spreadArrays(state.items, items);
var relatedValuesKeys_1 = Object.keys(relatedKeys);
if (relatedValuesKeys_1.length > 0) {
items.forEach(function (item) {
var id = item[idKey];
updating.relatedsTo[id] = relatedValuesKeys_1.reduce(function (acc, key) {
var valueType = relatedKeys[key];
if (valueType === 'one') {
acc[key] = {
item: {},
isLoading: false,
};
}
else if (valueType === 'many') {
acc[key] = {
items: [],
isLoading: false,
};
}
return acc;
}, {});
});
}
}
if (isFinished) {
if (Array.isArray(identifying)) {
updating.reading = state.reading.filter(function (id) { return !identifying.includes(id); });
}
else if (identifying) {
updating.reading = state.reading.filter(function (id) { return id !== identifying; });
}
else {
updating.isReadingBlindly = false;
}
}
}
if (operation === 'UPDATE' && !Array.isArray(identifying) && identifying) {
if (isLoading) {
updating.updating = __spreadArrays(state.updating, [identifying]);
}
if (isSuccess) {
updating.items = state.items.map(function (it) { return it[idKey] === identifying
? __assign(__assign({}, it), content) : it; });
}
if (isFinished) {
updating.updating = state.updating.filter(function (id) { return id !== identifying; });
}
}
if (operation === 'DELETE' && !Array.isArray(identifying) && identifying) {
if (isLoading) {
updating.deleting = __spreadArrays(state.deleting, [identifying]);
}
if (isSuccess) {
updating.items = state.items.filter(function (it) { return it[idKey] !== identifying; });
}
if (isFinished) {
updating.deleting = state.deleting.filter(function (id) { return id !== identifying; });
}
}
if (operation.startsWith('RELATED') && !Array.isArray(identifying) && updating.relatedsTo[identifying]) {
updating.relatedsTo = __assign({}, state.relatedsTo);
updating.relatedsTo[identifying] = __assign({}, updating.relatedsTo[identifying]);
updating.relatedsTo[identifying][relationshipKey] = __assign({}, updating.relatedsTo[identifying][relationshipKey]);
if (operation === 'RELATED' && isLoading) {
updating.relatedsTo[identifying][relationshipKey].isLoading = true;
}
if (isSuccess && !(content instanceof Error)) {
if (operation === 'RELATED_CREATED' && !Array.isArray(content)) {
var items = state.relatedsTo[identifying][relationshipKey].items;
updating.relatedsTo[identifying][relationshipKey].items = __spreadArrays(items, [
content,
]);
}
if (operation === 'RELATED_READ') {
if (Array.isArray(content)) {
updating.relatedsTo[identifying][relationshipKey].items = content;
}
else {
updating.relatedsTo[identifying][relationshipKey].item = content;
}
}
if (operation === 'RELATED_UPDATED' && !Array.isArray(content)) {
var items = state.relatedsTo[identifying][relationshipKey].items;
updating.relatedsTo[identifying][relationshipKey].items = items.map(function (it) { return it[idKey] === content[idKey] ? __assign(__assign({}, it), content) : it; });
}
if (operation === 'RELATED_DELETED' && !Array.isArray(content)) {
var items = state.relatedsTo[identifying][relationshipKey].items;
updating.relatedsTo[identifying][relationshipKey].items = items.filter(function (it) { return it[idKey] !== content[idKey]; });
}
}
if (isFinished) {
updating.relatedsTo[identifying][relationshipKey].isLoading = false;
}
}
var isDoingSomethingOnItself = updating.isCreating
|| updating.isReadingBlindly
|| updating.reading.length > 0
|| updating.updating.length > 0
|| updating.deleting.length > 0;
var isDoingSomethingOnRelateds = Object.keys(updating.relatedsTo).some(function (id) {
return Object.keys(updating.relatedsTo[id]).some(function (relatedKey) {
return updating.relatedsTo[id][relatedKey].isLoading;
});
});
updating.isLoading = isDoingSomethingOnItself || isDoingSomethingOnRelateds;
if (operation === 'SET_READING_ALL') {
updating.isReadingAll = true;
}
else if (operation === 'SET_NOT_READING_ALL') {
updating.isReadingAll = false;
}
else if (operation === 'SET_META') {
updating.meta = content;
}
else if (operation === 'CLEAR_ITEMS') {
updating.items = [];
updating.meta = {};
}
else if (operation === 'CLEAR_CURRENT_MESSAGE') {
updating.currentMessage = null;
}
else if (isFinished) {
var causedByError = content instanceof Error ? content : null;
var message = {
text: makeMessageText(content, operation, causedByError || isError),
causedByError: causedByError,
isError: isError,
};
updating.finishingLogs = __spreadArrays(state.finishingLogs, [message]);
updating.currentMessage = message;
}
return updating;
};
return {
initialState: initialState,
actionType: actionType,