@txo/service-graphql-react 2.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,6 @@
1
+ ## [2.2.3](https://github.com/technology-studio/service-graphql-react/compare/v2.2.2...v2.2.3) (2022-10-25)
2
+
3
+
4
+ ### Bug fixes
5
+
6
+ * migrate package ([#2](https://github.com/technology-studio/service-graphql-react/issues/2)) ([e761e34](https://github.com/technology-studio/service-graphql-react/commit/e761e34a539bfe58e82b9466bb0c2460ea38658f))
package/README.md ADDED
@@ -0,0 +1,5 @@
1
+ ![npm](https://img.shields.io/npm/v/@txo/service-graphql-react)
2
+ ![codecov](https://img.shields.io/codecov/c/github/technology-studio/service-graphql-react)
3
+ # Service graphql react #
4
+
5
+ Service graphql react
@@ -0,0 +1,6 @@
1
+ /**
2
+ * @Author: Erik Slovak <erik.slovak@technologystudio.sk>
3
+ * @Date: 2021-10-13T19:10:73+02:00
4
+ * @Copyright: Technology Studio
5
+ **/
6
+ export declare const serviceContext: (serviceName: string, serviceAttributes: Record<string, unknown>) => string;
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ /**
3
+ * @Author: Erik Slovak <erik.slovak@technologystudio.sk>
4
+ * @Date: 2021-10-13T19:10:73+02:00
5
+ * @Copyright: Technology Studio
6
+ **/
7
+ exports.__esModule = true;
8
+ exports.serviceContext = void 0;
9
+ var serviceContext = function (serviceName, serviceAttributes) { return ("".concat(serviceName, "(").concat(JSON.stringify(serviceAttributes), ")").replace(/\./g, '_')); };
10
+ exports.serviceContext = serviceContext;
11
+ //# sourceMappingURL=ContextHelper.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ContextHelper.js","sourceRoot":"","sources":["../../src/Api/ContextHelper.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;;AAEI,IAAM,cAAc,GAAG,UAAC,WAAmB,EAAE,iBAA0C,IAAa,OAAA,CACzG,UAAG,WAAW,cAAI,IAAI,CAAC,SAAS,CAAC,iBAAiB,CAAC,MAAG,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAC3E,EAF0G,CAE1G,CAAA;AAFY,QAAA,cAAc,kBAE1B"}
@@ -0,0 +1,10 @@
1
+ /**
2
+ * @Author: Erik Slovak <erik.slovak@technologystudio.sk>
3
+ * @Date: 2022-03-17T14:03:65+01:00
4
+ * @Copyright: Technology Studio
5
+ **/
6
+ import type { ServiceError } from '@txo/service-prop';
7
+ import type { ErrorMap, ErrorMapper } from '../Model/Types';
8
+ export declare const ignoreError: () => ErrorMapper;
9
+ export declare const validationError: (message?: string) => ErrorMapper;
10
+ export declare const applyErrorMap: (serviceErrorList: ServiceError[], errorMap: ErrorMap, onFieldErrors?: ((fieldErrors: Record<string, Record<string, string>>) => void) | undefined) => ServiceError[];
@@ -0,0 +1,103 @@
1
+ "use strict";
2
+ /**
3
+ * @Author: Erik Slovak <erik.slovak@technologystudio.sk>
4
+ * @Date: 2022-03-17T14:03:65+01:00
5
+ * @Copyright: Technology Studio
6
+ **/
7
+ var __assign = (this && this.__assign) || function () {
8
+ __assign = Object.assign || function(t) {
9
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
10
+ s = arguments[i];
11
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
12
+ t[p] = s[p];
13
+ }
14
+ return t;
15
+ };
16
+ return __assign.apply(this, arguments);
17
+ };
18
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
19
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
20
+ if (ar || !(i in from)) {
21
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
22
+ ar[i] = from[i];
23
+ }
24
+ }
25
+ return to.concat(ar || Array.prototype.slice.call(from));
26
+ };
27
+ var __importDefault = (this && this.__importDefault) || function (mod) {
28
+ return (mod && mod.__esModule) ? mod : { "default": mod };
29
+ };
30
+ exports.__esModule = true;
31
+ exports.applyErrorMap = exports.validationError = exports.ignoreError = void 0;
32
+ var functional_1 = require("@txo/functional");
33
+ var lodash_set_1 = __importDefault(require("lodash.set"));
34
+ var Types_1 = require("../Model/Types");
35
+ var normaliseErrorMap = function (errorMap) {
36
+ if ((0, functional_1.isObject)(errorMap)) {
37
+ return Object.keys(errorMap).reduce(function (normalisedErrorMap, key) {
38
+ (0, lodash_set_1["default"])(normalisedErrorMap, key, normaliseErrorMap(errorMap[key]));
39
+ return normalisedErrorMap;
40
+ }, {});
41
+ }
42
+ return errorMap;
43
+ };
44
+ var ignoreError = function () { return function () { return undefined; }; };
45
+ exports.ignoreError = ignoreError;
46
+ var validationError = function (message) { return function (_a) {
47
+ var error = _a.error;
48
+ var nextError = __assign(__assign({}, error), { message: message !== null && message !== void 0 ? message : error.message, meta: __assign(__assign({}, error.meta), { type: Types_1.VALIDATION_ERROR }) });
49
+ return nextError;
50
+ }; };
51
+ exports.validationError = validationError;
52
+ var getWithWildcardFallback = function (errorMap, path) {
53
+ if (errorMap === undefined) {
54
+ return undefined;
55
+ }
56
+ if (path) {
57
+ if ((0, functional_1.isObject)(errorMap)) {
58
+ var pathList = path.split('.');
59
+ var currentPath = pathList.shift();
60
+ var keyList = Object.keys(errorMap);
61
+ var currentKey = currentPath && keyList.includes(currentPath) ? currentPath : '*';
62
+ return getWithWildcardFallback(errorMap[currentKey], pathList.join('.'));
63
+ }
64
+ else {
65
+ return undefined;
66
+ }
67
+ }
68
+ return typeof errorMap === 'function' ? errorMap : undefined;
69
+ };
70
+ var applyErrorMap = function (serviceErrorList, errorMap, onFieldErrors) {
71
+ var normalisedErrorMap = normaliseErrorMap(errorMap);
72
+ var modified = false;
73
+ var fieldErrors = {};
74
+ var nextServiceErrorList = serviceErrorList
75
+ .reduce(function (nextServiceErrorList, serviceError) {
76
+ var _a;
77
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
78
+ var graphQlError = serviceError.data;
79
+ var path = __spreadArray(__spreadArray([], ((_a = graphQlError === null || graphQlError === void 0 ? void 0 : graphQlError.path) !== null && _a !== void 0 ? _a : []), true), [serviceError.key], false).join('.');
80
+ var errorMapper = getWithWildcardFallback(normalisedErrorMap, path);
81
+ if (errorMapper) {
82
+ var nextServiceError = errorMapper({
83
+ error: serviceError,
84
+ fieldErrors: fieldErrors,
85
+ path: path
86
+ });
87
+ if (nextServiceError !== serviceError) {
88
+ modified = true;
89
+ }
90
+ nextServiceError && nextServiceErrorList.push(nextServiceError);
91
+ }
92
+ else {
93
+ nextServiceErrorList.push(serviceError);
94
+ }
95
+ return nextServiceErrorList;
96
+ }, []);
97
+ if (onFieldErrors && Object.keys(fieldErrors).length > 0) {
98
+ onFieldErrors(fieldErrors);
99
+ }
100
+ return modified ? nextServiceErrorList : serviceErrorList;
101
+ };
102
+ exports.applyErrorMap = applyErrorMap;
103
+ //# sourceMappingURL=ErrorMapHelper.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ErrorMapHelper.js","sourceRoot":"","sources":["../../src/Api/ErrorMapHelper.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;;;;;;;;;;;;;;;;;;;;;;;;;AAKH,8CAA0C;AAC1C,0DAA4B;AAM5B,wCAEuB;AAEvB,IAAM,iBAAiB,GAAG,UAAC,QAAkB;IAC3C,IAAI,IAAA,qBAAQ,EAAC,QAAQ,CAAC,EAAE;QACtB,OAAO,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,UAAC,kBAA+C,EAAE,GAAG;YACvF,IAAA,uBAAG,EAAC,kBAAkB,EAAE,GAAG,EAAE,iBAAiB,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAA;YAC9D,OAAO,kBAAkB,CAAA;QAC3B,CAAC,EAAE,EAAE,CAAC,CAAA;KACP;IACD,OAAO,QAAQ,CAAA;AACjB,CAAC,CAAA;AAEM,IAAM,WAAW,GAAG,cAAmB,OAAA,cAAM,OAAA,SAAS,EAAT,CAAS,EAAf,CAAe,CAAA;AAAh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 * @Date: 2021-09-28T20:09:40+02:00
4
+ * @Copyright: Technology Studio
5
+ **/
6
+ import type { DocumentNode } from 'graphql';
7
+ export declare const getName: (query: DocumentNode) => string;
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ /**
3
+ * @Author: Erik Slovak <erik.slovak@technologystudio.sk>
4
+ * @Date: 2021-09-28T20:09:40+02:00
5
+ * @Copyright: Technology Studio
6
+ **/
7
+ exports.__esModule = true;
8
+ exports.getName = void 0;
9
+ var upperCaseFirst = function (str) { return str.charAt(0).toUpperCase() + str.slice(1); };
10
+ var pascalCase = function (string) { return ("".concat(string)
11
+ .replace(/[-_]+/g, ' ')
12
+ .replace(/[^\w\s]/g, '')
13
+ .replace(/\s+(.)(\w*)/g, function (_$1, $2, $3) { return "".concat($2.toUpperCase() + $3.toLowerCase()); })
14
+ .replace(/\w/, function (s) { return s.toUpperCase(); })); };
15
+ var getName = function (query) {
16
+ var _a;
17
+ var definition = query.definitions
18
+ .find(function (definition) { return (definition.kind === 'OperationDefinition'); });
19
+ var operationName = (_a = definition === null || definition === void 0 ? void 0 : definition.name) === null || _a === void 0 ? void 0 : _a.value.split('_').map(pascalCase).join('.');
20
+ return operationName !== null && operationName !== void 0 ? operationName : upperCaseFirst(definition.operation);
21
+ };
22
+ exports.getName = getName;
23
+ //# sourceMappingURL=OperationHelper.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"OperationHelper.js","sourceRoot":"","sources":["../../src/Api/OperationHelper.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;;AAOH,IAAM,cAAc,GAAG,UAAC,GAAW,IAAa,OAAA,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,EAA1C,CAA0C,CAAA;AAC1F,IAAM,UAAU,GAAG,UAAC,MAAc,IAAa,OAAA,CAC7C,UAAG,MAAM,CAAE;KACR,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC;KACtB,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC;KACvB,OAAO,CACN,cAAc,EACd,UAAC,GAAG,EAAE,EAAU,EAAE,EAAU,IAAK,OAAA,UAAG,EAAE,CAAC,WAAW,EAAE,GAAG,EAAE,CAAC,WAAW,EAAE,CAAE,EAAxC,CAAwC,CAC1E;KACA,OAAO,CAAC,IAAI,EAAE,UAAA,CAAC,IAAI,OAAA,CAAC,CAAC,WAAW,EAAE,EAAf,CAAe,CAAC,CACvC,EAT8C,CAS9C,CAAA;AAEM,IAAM,OAAO,GAAG,UAAC,KAAmB;;IACzC,IAAM,UAAU,GAAG,KAAK,CAAC,WAAW;SACjC,IAAI,CAAC,UAAA,UAAU,IAAI,OAAA,CAClB,UAAU,CAAC,IAAI,KAAK,qBAAqB,CAC1C,EAFmB,CAEnB,CAA4B,CAAA;IAC/B,IAAM,aAAa,GAAG,MAAA,UAAU,aAAV,UAAU,uBAAV,UAAU,CAAE,IAAI,0CAAE,KAAK,CAC1C,KAAK,CAAC,GAAG,EACT,GAAG,CAAC,UAAU,EACd,IAAI,CAAC,GAAG,CAAC,CAAA;IACZ,OAAO,aAAa,aAAb,aAAa,cAAb,aAAa,GAAI,cAAc,CAAC,UAAU,CAAC,SAAS,CAAC,CAAA;AAC9D,CAAC,CAAA;AAVY,QAAA,OAAO,WAUnB"}
@@ -0,0 +1,25 @@
1
+ /**
2
+ * @Author: Erik Slovak <erik.slovak@technologystudio.sk>
3
+ * @Date: 2021-08-24T13:08:91+02:00
4
+ * @Copyright: Technology Studio
5
+ **/
6
+ import type { DependencyList } from 'react';
7
+ import type { CallAttributes, ServiceProp } from '@txo/service-prop';
8
+ import type { MutationOptions as ApolloMutationOptions, TypedDocumentNode, MutationResult, MutationFunctionOptions as MutateFunctionOptions, FetchResult } from '@apollo/client';
9
+ import type { ErrorMap } from '../Model/Types';
10
+ export declare type MutationServiceProp<ATTRIBUTES, DATA, CALL_ATTRIBUTES extends CallAttributes<ATTRIBUTES>> = Omit<ServiceProp<ATTRIBUTES, DATA, CALL_ATTRIBUTES, FetchResult<DATA>>, 'clear' | 'options' | 'clearException' | 'exception'> & {
11
+ mutation: MutationResult<DATA>;
12
+ };
13
+ export declare type MutateFunction<DATA, ATTRIBUTES> = (options?: MutateFunctionOptions<DATA, ATTRIBUTES>) => Promise<FetchResult<DATA>>;
14
+ export declare type MutationOptions<DATA, ATTRIBUTES> = {
15
+ onFieldErrors?: (fieldErrors: Record<string, Record<string, string>>) => void;
16
+ options?: Omit<ApolloMutationOptions<DATA, ATTRIBUTES>, 'mutation'>;
17
+ errorMap?: ErrorMap;
18
+ mutateFactory?: (mutate: MutateFunction<DATA, ATTRIBUTES>) => MutateFunction<DATA, ATTRIBUTES>;
19
+ onFieldErrorsDependencyList?: DependencyList;
20
+ errorMapDependencyList?: DependencyList;
21
+ };
22
+ export declare const useServiceMutation: <ATTRIBUTES extends Record<string, unknown>, DATA, CALL_ATTRIBUTES extends Partial<ATTRIBUTES & {
23
+ context?: string | undefined;
24
+ onFieldErrors?: ((fieldErrors: Record<string, Record<string, string>>) => void) | undefined;
25
+ }>>(mutationDocument: TypedDocumentNode<DATA, ATTRIBUTES>, options?: MutationOptions<DATA, ATTRIBUTES> | undefined) => MutationServiceProp<ATTRIBUTES, DATA, CALL_ATTRIBUTES>;
@@ -0,0 +1,123 @@
1
+ "use strict";
2
+ /**
3
+ * @Author: Erik Slovak <erik.slovak@technologystudio.sk>
4
+ * @Date: 2021-08-24T13:08:91+02:00
5
+ * @Copyright: Technology Studio
6
+ **/
7
+ var __assign = (this && this.__assign) || function () {
8
+ __assign = Object.assign || function(t) {
9
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
10
+ s = arguments[i];
11
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
12
+ t[p] = s[p];
13
+ }
14
+ return t;
15
+ };
16
+ return __assign.apply(this, arguments);
17
+ };
18
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
19
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
20
+ return new (P || (P = Promise))(function (resolve, reject) {
21
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
22
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
23
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
24
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
25
+ });
26
+ };
27
+ var __generator = (this && this.__generator) || function (thisArg, body) {
28
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
29
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
30
+ function verb(n) { return function (v) { return step([n, v]); }; }
31
+ function step(op) {
32
+ if (f) throw new TypeError("Generator is already executing.");
33
+ while (_) try {
34
+ 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;
35
+ if (y = 0, t) op = [op[0] & 2, t.value];
36
+ switch (op[0]) {
37
+ case 0: case 1: t = op; break;
38
+ case 4: _.label++; return { value: op[1], done: false };
39
+ case 5: _.label++; y = op[1]; op = [0]; continue;
40
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
41
+ default:
42
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
43
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
44
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
45
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
46
+ if (t[2]) _.ops.pop();
47
+ _.trys.pop(); continue;
48
+ }
49
+ op = body.call(thisArg, _);
50
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
51
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
52
+ }
53
+ };
54
+ exports.__esModule = true;
55
+ exports.useServiceMutation = void 0;
56
+ var react_1 = require("react");
57
+ var hooks_react_1 = require("@txo/hooks-react");
58
+ var client_1 = require("@apollo/client");
59
+ var service_error_handler_react_1 = require("@txo-peer-dep/service-error-handler-react");
60
+ var service_graphql_1 = require("@txo/service-graphql");
61
+ var ContextHelper_1 = require("../Api/ContextHelper");
62
+ var OperationHelper_1 = require("../Api/OperationHelper");
63
+ var ErrorMapHelper_1 = require("../Api/ErrorMapHelper");
64
+ var calculateContext = function (mutation, variables) { return ((0, ContextHelper_1.serviceContext)((0, OperationHelper_1.getName)(mutation), variables !== null && variables !== void 0 ? variables : {})); };
65
+ var useServiceMutation = function (mutationDocument, options) {
66
+ var _a = options !== null && options !== void 0 ? options : {}, defaultOnFieldErrors = _a.onFieldErrors, onFieldErrorsDependencyList = _a.onFieldErrorsDependencyList, errorMap = _a.errorMap, errorMapDependencyList = _a.errorMapDependencyList, mutationOptions = _a.options, mutateFactory = _a.mutateFactory;
67
+ var exceptionRef = (0, react_1.useRef)(null);
68
+ var memoizedErrorMap = (0, react_1.useMemo)(function () { return errorMap; },
69
+ // eslint-disable-next-line react-hooks/exhaustive-deps
70
+ errorMapDependencyList !== null && errorMapDependencyList !== void 0 ? errorMapDependencyList : []);
71
+ var memoizedDefaultOnFieldErrors = (0, react_1.useMemo)(function () { return defaultOnFieldErrors; },
72
+ // eslint-disable-next-line react-hooks/exhaustive-deps
73
+ onFieldErrorsDependencyList !== null && onFieldErrorsDependencyList !== void 0 ? onFieldErrorsDependencyList : []);
74
+ var _b = (0, client_1.useMutation)(mutationDocument, mutationOptions), mutate = _b[0], mutation = _b[1];
75
+ var _c = (0, react_1.useContext)(service_error_handler_react_1.ErrorHandlerContext), addServiceErrorException = _c.addServiceErrorException, removeServiceErrorException = _c.removeServiceErrorException;
76
+ var memoizedOptions = (0, hooks_react_1.useMemoObject)(mutationOptions);
77
+ var wrappedCall = (0, react_1.useCallback)(function (variables, callAttributes) { return __awaiter(void 0, void 0, void 0, function () {
78
+ var attributes, onFieldErrors, context, operationName, mutateWithErrorProcessor, nextMutate;
79
+ var _a, _b;
80
+ return __generator(this, function (_c) {
81
+ attributes = __assign({ variables: variables, mutation: mutationDocument }, memoizedOptions);
82
+ onFieldErrors = (_a = callAttributes === null || callAttributes === void 0 ? void 0 : callAttributes.onFieldErrors) !== null && _a !== void 0 ? _a : memoizedDefaultOnFieldErrors;
83
+ context = calculateContext(mutationDocument, variables);
84
+ exceptionRef.current && removeServiceErrorException(context);
85
+ exceptionRef.current = null;
86
+ operationName = (0, OperationHelper_1.getName)(mutationDocument);
87
+ mutateWithErrorProcessor = function (options) { return __awaiter(void 0, void 0, void 0, function () {
88
+ return __generator(this, function (_a) {
89
+ return [2 /*return*/, ((0, service_graphql_1.operationPromiseProcessor)(mutate(options), {
90
+ operationName: operationName,
91
+ context: context
92
+ }))];
93
+ });
94
+ }); };
95
+ nextMutate = (_b = mutateFactory === null || mutateFactory === void 0 ? void 0 : mutateFactory(mutateWithErrorProcessor)) !== null && _b !== void 0 ? _b : mutateWithErrorProcessor;
96
+ return [2 /*return*/, (0, service_graphql_1.operationPromiseProcessor)(nextMutate(attributes), {
97
+ operationName: operationName,
98
+ context: context
99
+ })["catch"](function (serviceErrorException) { return __awaiter(void 0, void 0, void 0, function () {
100
+ return __generator(this, function (_a) {
101
+ if (memoizedErrorMap) {
102
+ serviceErrorException.serviceErrorList = (0, ErrorMapHelper_1.applyErrorMap)(serviceErrorException.serviceErrorList, memoizedErrorMap, onFieldErrors);
103
+ }
104
+ addServiceErrorException(serviceErrorException);
105
+ exceptionRef.current = serviceErrorException;
106
+ throw serviceErrorException;
107
+ });
108
+ }); })];
109
+ });
110
+ }); }, [mutationDocument, memoizedOptions, memoizedDefaultOnFieldErrors, removeServiceErrorException, mutateFactory, mutate, memoizedErrorMap, addServiceErrorException]);
111
+ var memoizedMutation = (0, hooks_react_1.useMemoObject)(mutation);
112
+ return (0, react_1.useMemo)(function () {
113
+ var _a;
114
+ return ({
115
+ mutation: memoizedMutation,
116
+ data: (_a = memoizedMutation.data) !== null && _a !== void 0 ? _a : null,
117
+ fetching: memoizedMutation.loading,
118
+ call: wrappedCall
119
+ });
120
+ }, [memoizedMutation, wrappedCall]);
121
+ };
122
+ exports.useServiceMutation = useServiceMutation;
123
+ //# sourceMappingURL=UseServiceMutation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"UseServiceMutation.js","sourceRoot":"","sources":["../../src/Hooks/UseServiceMutation.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGH,+BAKc;AAMd,gDAAgD;AAUhD,yCAEuB;AACvB,yFAA+E;AAC/E,wDAAgE;AAEhE,sDAAqD;AACrD,0DAAgD;AAEhD,wDAAqD;AAErD,IAAM,gBAAgB,GAAG,UAAC,QAAsB,EAAE,SAAmC,IAAa,OAAA,CAChG,IAAA,8BAAc,EAAC,IAAA,yBAAO,EAAC,QAAQ,CAAC,EAAE,SAAS,aAAT,SAAS,cAAT,SAAS,GAAI,EAAE,CAAC,CACnD,EAFiG,CAEjG,CAAA;AAmBM,IAAM,kBAAkB,GAAG,UAK9B,gBAAqD,EACrD,OAA2C;IAEvC,IAAA,KAOF,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,EAAE,EANA,oBAAoB,mBAAA,EACnC,2BAA2B,iCAAA,EAC3B,QAAQ,cAAA,EACR,sBAAsB,4BAAA,EACb,eAAe,aAAA,EACxB,aAAa,mBACE,CAAA;IACjB,IAAM,YAAY,GAAG,IAAA,cAAM,EAA+B,IAAI,CAAC,CAAA;IAC/D,IAAM,gBAAgB,GAAG,IAAA,eAAO,EAC9B,cAAM,OAAA,QAAQ,EAAR,CAAQ;IACd,uDAAuD;IACvD,sBAAsB,aAAtB,sBAAsB,cAAtB,sBA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AAO,IAAA,2CAAyB,EAAC,UAAU,CAAC,UAAU,CAAC,EAAE;oBACvD,aAAa,eAAA;oBACb,OAAO,SAAA;iBACR,CAAC,CACC,OAAK,CAAA,CAAC,UAAO,qBAA4C;;wBACxD,IAAI,gBAAgB,EAAE;4BACpB,qBAAqB,CAAC,gBAAgB,GAAG,IAAA,8BAAa,EACpD,qBAAqB,CAAC,gBAAgB,EACtC,gBAAgB,EAChB,aAAa,CACd,CAAA;yBACF;wBACD,wBAAwB,CAAC,qBAAqB,CAAC,CAAA;wBAC/C,YAAY,CAAC,OAAO,GAAG,qBAAqB,CAAA;wBAC5C,MAAM,qBAAqB,CAAA;;qBAC5B,CAAC,EAAA;;SACL,EAAE,CAAC,gBAAgB,EAAE,eAAe,EAAE,4BAA4B,EAAE,2BAA2B,EAAE,aAAa,EAAE,MAAM,EAAE,gBAAgB,EAAE,wBAAwB,CAAC,CAAC,CAAA;IAErK,IAAM,gBAAgB,GAAG,IAAA,2BAAa,EAA+B,QAAQ,CAAC,CAAA;IAE9E,OAAO,IAAA,eAAO,EAAC;;QAAM,OAAA,CAAC;YACpB,QAAQ,EAAE,gBAAgB;YAC1B,IAAI,EAAE,MAAA,gBAAgB,CAAC,IAAI,mCAAI,IAAI;YACnC,QAAQ,EAAE,gBAAgB,CAAC,OAAO;YAClC,IAAI,EAAE,WAAW;SAClB,CAAC,CAAA;KAAA,EAAE,CAAC,gBAAgB,EAAE,WAAW,CAAC,CAAC,CAAA;AACtC,CAAC,CAAA;AA/EY,QAAA,kBAAkB,sBA+E9B"}
@@ -0,0 +1,20 @@
1
+ /**
2
+ * @Author: Erik Slovak <erik.slovak@technologystudio.sk>
3
+ * @Date: 2021-09-01T16:09:57+02:00
4
+ * @Copyright: Technology Studio
5
+ **/
6
+ import type { QueryHookOptions, TypedDocumentNode, QueryResult } from '@apollo/client';
7
+ import type { Get } from 'type-fest';
8
+ import type { CallAttributes, ServiceProp } from '@txo/service-prop';
9
+ export declare type QueryServiceProp<ATTRIBUTES, DATA, MAPPED_DATA, CALL_ATTRIBUTES extends CallAttributes<ATTRIBUTES>> = Omit<ServiceProp<ATTRIBUTES, MAPPED_DATA, CALL_ATTRIBUTES>, 'call' | 'clear' | 'options' | 'clearException'> & {
10
+ query: QueryResult<DATA, ATTRIBUTES>;
11
+ };
12
+ declare type QueryOptions<DATA, ATTRIBUTES, DATA_PATH extends string> = {
13
+ options?: QueryHookOptions<DATA, ATTRIBUTES>;
14
+ dataPath: DATA_PATH;
15
+ };
16
+ export declare const useServiceQuery: <ATTRIBUTES extends Record<string, unknown>, DATA, CALL_ATTRIBUTES extends Partial<ATTRIBUTES & {
17
+ context?: string | undefined;
18
+ onFieldErrors?: ((fieldErrors: Record<string, Record<string, string>>) => void) | undefined;
19
+ }>, DATA_PATH extends string>(queryDocument: TypedDocumentNode<DATA, ATTRIBUTES>, options: QueryOptions<DATA, ATTRIBUTES, DATA_PATH>) => QueryServiceProp<ATTRIBUTES, DATA, import("type-fest/source/get").GetWithPath<DATA, DATA_PATH extends string ? import("type-fest").Split<import("type-fest/source/get").FixPathSquareBrackets<DATA_PATH>, "."> : DATA_PATH, {}>, CALL_ATTRIBUTES>;
20
+ export {};
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ /**
3
+ * @Author: Erik Slovak <erik.slovak@technologystudio.sk>
4
+ * @Date: 2021-09-01T16:09:57+02:00
5
+ * @Copyright: Technology Studio
6
+ **/
7
+ var __importDefault = (this && this.__importDefault) || function (mod) {
8
+ return (mod && mod.__esModule) ? mod : { "default": mod };
9
+ };
10
+ exports.__esModule = true;
11
+ exports.useServiceQuery = void 0;
12
+ var react_1 = require("react");
13
+ var client_1 = require("@apollo/client");
14
+ var lodash_get_1 = __importDefault(require("lodash.get"));
15
+ var service_prop_1 = require("@txo/service-prop");
16
+ var service_graphql_1 = require("@txo-peer-dep/service-graphql");
17
+ var hooks_react_1 = require("@txo/hooks-react");
18
+ var service_error_handler_react_1 = require("@txo-peer-dep/service-error-handler-react");
19
+ var ContextHelper_1 = require("../Api/ContextHelper");
20
+ var OperationHelper_1 = require("../Api/OperationHelper");
21
+ var calculateContext = function (query, variables) { return ((0, ContextHelper_1.serviceContext)((0, OperationHelper_1.getName)(query), variables !== null && variables !== void 0 ? variables : {})); };
22
+ var isServiceErrorListEqual = function (a, b) {
23
+ if (a.length !== b.length) {
24
+ return false;
25
+ }
26
+ if (a.every(function (error, index) { return (b[index].key === error.key) && (b[index].message === error.message); })) {
27
+ return true;
28
+ }
29
+ return false;
30
+ };
31
+ // TODO: find a better way to parse type of dataPath (from attribute)
32
+ var useServiceQuery = function (queryDocument, options) {
33
+ var dataPath = options.dataPath, queryOptions = options.options;
34
+ var query = (0, client_1.useQuery)(queryDocument, queryOptions);
35
+ var shownExceptionListRef = (0, react_1.useRef)([]);
36
+ var _a = (0, react_1.useContext)(service_error_handler_react_1.ErrorHandlerContext), addServiceErrorException = _a.addServiceErrorException, removeServiceErrorException = _a.removeServiceErrorException;
37
+ var memoizedVariables = (0, hooks_react_1.useMemoObject)(queryOptions === null || queryOptions === void 0 ? void 0 : queryOptions.variables);
38
+ var memoizedQuery = (0, hooks_react_1.useMemoObject)(query);
39
+ var context = (0, react_1.useMemo)(function () { return (calculateContext(queryDocument, memoizedVariables)); }, [queryDocument, memoizedVariables]);
40
+ var exception = (0, react_1.useMemo)(function () {
41
+ var operationName = (0, OperationHelper_1.getName)(queryDocument);
42
+ if (memoizedQuery.error) {
43
+ var errorList = service_graphql_1.configManager.config.errorResponseTranslator(memoizedQuery.error, {
44
+ context: context,
45
+ operationName: operationName
46
+ });
47
+ var exception_1 = new service_prop_1.ServiceErrorException({
48
+ serviceErrorList: errorList,
49
+ serviceName: operationName,
50
+ context: context
51
+ });
52
+ return exception_1;
53
+ }
54
+ return null;
55
+ }, [context, memoizedQuery, queryDocument]);
56
+ (0, react_1.useLayoutEffect)(function () {
57
+ if (exception && !shownExceptionListRef.current.find(function (shownException) { return (isServiceErrorListEqual(shownException.serviceErrorList, exception.serviceErrorList)); })) {
58
+ addServiceErrorException(exception);
59
+ shownExceptionListRef.current.push(exception);
60
+ }
61
+ return function () {
62
+ exception && removeServiceErrorException(context);
63
+ };
64
+ }, [addServiceErrorException, context, exception, memoizedVariables, queryDocument, removeServiceErrorException]);
65
+ return (0, react_1.useMemo)(function () { return ({
66
+ query: memoizedQuery,
67
+ data: (0, lodash_get_1["default"])(memoizedQuery.data, dataPath),
68
+ fetching: memoizedQuery.loading,
69
+ exception: exception
70
+ }); }, [memoizedQuery, exception, dataPath]);
71
+ };
72
+ exports.useServiceQuery = useServiceQuery;
73
+ //# sourceMappingURL=UseServiceQuery.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"UseServiceQuery.js","sourceRoot":"","sources":["../../src/Hooks/UseServiceQuery.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;;;;;AAEH,+BAKc;AAOd,yCAEuB;AACvB,0DAA4B;AAO5B,kDAE0B;AAC1B,iEAA6D;AAC7D,gDAEyB;AACzB,yFAA+E;AAG/E,sDAAqD;AACrD,0DAAgD;AAEhD,IAAM,gBAAgB,GAAG,UAAC,KAAmB,EAAE,SAA8C,IAAa,OAAA,CACxG,IAAA,8BAAc,EAAC,IAAA,yBAAO,EAAC,KAAK,CAAC,EAAE,SAAS,aAAT,SAAS,cAAT,SAAS,GAAI,EAAE,CAAC,CAChD,EAFyG,CAEzG,CAAA;AAaD,IAAM,uBAAuB,GAAG,UAAC,CAAiB,EAAE,CAAiB;IACnE,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,MAAM,EAAE;QACzB,OAAO,KAAK,CAAA;KACb;IACD,IAAI,CAAC,CAAC,KAAK,CAAC,UAAC,KAAK,EAAE,KAAK,IAAK,OAAA,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,GAAG,KAAK,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,OAAO,KAAK,KAAK,CAAC,OAAO,CAAC,EAApE,CAAoE,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AAS,CAAA;SACjB;QACD,OAAO,IAAI,CAAA;IACb,CAAC,EAAE,CAAC,OAAO,EAAE,aAAa,EAAE,aAAa,CAAC,CAAC,CAAA;IAC3C,IAAA,uBAAe,EAAC;QACd,IAAI,SAAS,IAAI,CAAC,qBAAqB,CAAC,OAAO,CAAC,IAAI,CAAC,UAAA,cAAc,IAAI,OAAA,CACrE,uBAAuB,CAAC,cAAc,CAAC,gBAAgB,EAAE,SAAS,CAAC,gBAAgB,CAAC,CACrF,EAFsE,CAEtE,CAAC,EAAE;YACF,wBAAwB,CAAC,SAAS,CAAC,CAAA;YACnC,qBAAqB,CAAC,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,CAAA;SAC9C;QACD,OAAO;YACL,SAAS,IAAI,2BAA2B,CAAC,OAAO,CAAC,CAAA;QACnD,CAAC,CAAA;IACH,CAAC,EAAE,CAAC,wBAAwB,EAAE,OAAO,EAAE,SAAS,EAAE,iBAAiB,EAAE,aAAa,EAAE,2BAA2B,CAAC,CAAC,CAAA;IAEjH,OAAO,IAAA,eAAO,EAAC,cAAM,OAAA,CAAC;QACpB,KAAK,EAAE,aAAa;QACpB,IAAI,EAAE,IAAA,uBAAG,EAAC,aAAa,CAAC,IAAI,EAAE,QAAQ,CAAC;QACvC,QAAQ,EAAE,aAAa,CAAC,OAAO;QAC/B,SAAS,WAAA;KACV,CAAC,EALmB,CAKnB,EAAE,CAAC,aAAa,EAAE,SAAS,EAAE,QAAQ,CAAC,CAAC,CAAA;AAC3C,CAAC,CAAA;AA1DY,QAAA,eAAe,mBA0D3B"}
@@ -0,0 +1,15 @@
1
+ /**
2
+ * @Author: Erik Slovak <erik.slovak@technologystudio.sk>
3
+ * @Date: 2022-03-17T10:03:96+01:00
4
+ * @Copyright: Technology Studio
5
+ **/
6
+ import type { ServiceError } from '@txo/service-prop';
7
+ export declare type ErrorMapper = ((options: {
8
+ error: ServiceError;
9
+ fieldErrors?: Record<string, Record<string, string>>;
10
+ path: string;
11
+ }) => ServiceError | undefined) | undefined;
12
+ export declare type ErrorMap = {
13
+ [key: string]: ErrorMap;
14
+ } | ErrorMapper;
15
+ export declare const VALIDATION_ERROR = "VALIDATION_ERROR";
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ /**
3
+ * @Author: Erik Slovak <erik.slovak@technologystudio.sk>
4
+ * @Date: 2022-03-17T10:03:96+01:00
5
+ * @Copyright: Technology Studio
6
+ **/
7
+ exports.__esModule = true;
8
+ exports.VALIDATION_ERROR = void 0;
9
+ exports.VALIDATION_ERROR = 'VALIDATION_ERROR';
10
+ //# sourceMappingURL=Types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Types.js","sourceRoot":"","sources":["../../src/Model/Types.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;;AAYU,QAAA,gBAAgB,GAAG,kBAAkB,CAAA"}
package/lib/index.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ /**
2
+ * @Author: Erik Slovak <erik.slovak@technologystudio.sk>
3
+ * @Date: 2022-01-24T13:01:19+01:00
4
+ * @Copyright: Technology Studio
5
+ **/
6
+ export { getName } from './Api/OperationHelper';
7
+ export * from './Api/ErrorMapHelper';
8
+ export * from './Hooks/UseServiceMutation';
9
+ export { useServiceQuery, QueryServiceProp, } from './Hooks/UseServiceQuery';
10
+ export * from './Model/Types';
package/lib/index.js ADDED
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ /**
3
+ * @Author: Erik Slovak <erik.slovak@technologystudio.sk>
4
+ * @Date: 2022-01-24T13:01:19+01:00
5
+ * @Copyright: Technology Studio
6
+ **/
7
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
8
+ if (k2 === undefined) k2 = k;
9
+ var desc = Object.getOwnPropertyDescriptor(m, k);
10
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
11
+ desc = { enumerable: true, get: function() { return m[k]; } };
12
+ }
13
+ Object.defineProperty(o, k2, desc);
14
+ }) : (function(o, m, k, k2) {
15
+ if (k2 === undefined) k2 = k;
16
+ o[k2] = m[k];
17
+ }));
18
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
19
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
20
+ };
21
+ exports.__esModule = true;
22
+ exports.useServiceQuery = exports.getName = void 0;
23
+ var OperationHelper_1 = require("./Api/OperationHelper");
24
+ __createBinding(exports, OperationHelper_1, "getName");
25
+ __exportStar(require("./Api/ErrorMapHelper"), exports);
26
+ __exportStar(require("./Hooks/UseServiceMutation"), exports);
27
+ var UseServiceQuery_1 = require("./Hooks/UseServiceQuery");
28
+ __createBinding(exports, UseServiceQuery_1, "useServiceQuery");
29
+ __exportStar(require("./Model/Types"), exports);
30
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;;;;;;;;;;;;;;;;AAEH,yDAA+C;AAAtC,uDAAO;AAChB,uDAAoC;AACpC,6DAA0C;AAC1C,2DAGgC;AAF9B,+DAAe;AAGjB,gDAA6B"}
package/package.json ADDED
@@ -0,0 +1,99 @@
1
+ {
2
+ "name": "@txo/service-graphql-react",
3
+ "version": "2.2.3",
4
+ "description": "Technology Studio - Service graphql react",
5
+ "main": "lib/index.js",
6
+ "typings": "lib/index.d.ts",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/technology-studio/service-graphql-react.git"
10
+ },
11
+ "author": {
12
+ "name": "Technology Studio",
13
+ "email": "npm@technologystudio.sk",
14
+ "url": "https://github.com/technology-studio/"
15
+ },
16
+ "license": "MIT",
17
+ "private": false,
18
+ "scripts": {
19
+ "build": "yarn build:clean && yarn build:lib",
20
+ "build:clean": "yarn rimraf lib",
21
+ "build:lib": "yarn tsc",
22
+ "build:watch": "yarn tsc --watch",
23
+ "test": "jest",
24
+ "test:watch": "concurrently \"yarn build:watch\" \"jest --watch\"",
25
+ "coverage": "jest --coverage && open coverage/lcov-report/index.html || xdg-open coverage/lcov-report/index.html",
26
+ "compare-boilerplate-version": "./scripts/compare-boilerplate-version.sh",
27
+ "lint": "eslint --format=node_modules/eslint-formatter-pretty --ext .jsx,.js,.ts,.tsx .",
28
+ "fixcode": "eslint --format=node_modules/eslint-formatter-pretty --ext .jsx,.js,.ts,.tsx . --fix",
29
+ "git-hook": "yarn -s lint-staged",
30
+ "prepare": "husky install && yarn build",
31
+ "print-txo-packages": "yarn list 2> /dev/null|grep @txo|sed 's/.*\\(@txo[^@]*\\)@^*\\([^ ]*\\).*/\\1@\\2/g'|sort|uniq",
32
+ "sanity": "yarn lint && yarn build && tsc --noEmit && yarn test && yarn compare-boilerplate-version && echo 'success'",
33
+ "semantic-release": "semantic-release",
34
+ "update-boilerplate-version": "./scripts/update-boilerplate-version.sh"
35
+ },
36
+ "dependencies": {
37
+ "@txo/hooks-react": "^2.3.4",
38
+ "@txo/service-graphql": "^4.3.1",
39
+ "@txo/service-prop": "^2.2.1",
40
+ "@txo/types": "^1.3.0",
41
+ "lodash.get": "^4.4.2",
42
+ "lodash.set": "^4.3.2",
43
+ "type-fest": "^3.1.0"
44
+ },
45
+ "peerDependencies": {
46
+ "@apollo/client": "^3.6.9",
47
+ "@txo-peer-dep/service-error-handler-react": "^1.2.0",
48
+ "@txo-peer-dep/service-graphql": "^3.2.1",
49
+ "graphql": "^16.6.0"
50
+ },
51
+ "devDependencies": {
52
+ "@apollo/client": "^3.7.0",
53
+ "@commitlint/cli": "^17.1.2",
54
+ "@commitlint/config-conventional": "^17.1.0",
55
+ "@semantic-release/changelog": "^6.0.1",
56
+ "@semantic-release/git": "^10.0.1",
57
+ "@txo-peer-dep/log": "^4.0.0",
58
+ "@txo-peer-dep/service-error-handler-react": "^1.2.0",
59
+ "@txo-peer-dep/service-graphql": "^3.2.1",
60
+ "@txo/log-console": "^3.0.0",
61
+ "@types/jest": "^29.2.0",
62
+ "@types/lodash.get": "^4.4.7",
63
+ "@types/lodash.set": "^4.3.7",
64
+ "@types/react": "^18.0.21",
65
+ "@typescript-eslint/eslint-plugin": "^5.40.1",
66
+ "@typescript-eslint/parser": "^5.40.1",
67
+ "commitizen": "^4.2.5",
68
+ "concurrently": "^7.4.0",
69
+ "eslint": "^8.25.0",
70
+ "eslint-config-txo-typescript-react": "^1.0.14",
71
+ "eslint-formatter-pretty": "^4.1.0",
72
+ "eslint-plugin-eslint-comments": "^3.2.0",
73
+ "eslint-plugin-import": "^2.26.0",
74
+ "eslint-plugin-jest": "^27.1.3",
75
+ "eslint-plugin-jsx-a11y": "^6.6.1",
76
+ "eslint-plugin-n": "^15.3.0",
77
+ "eslint-plugin-promise": "^6.1.1",
78
+ "eslint-plugin-react": "^7.31.10",
79
+ "eslint-plugin-react-hooks": "^4.6.0",
80
+ "eslint-plugin-redux-saga": "^1.3.2",
81
+ "graphql": "^16.6.0",
82
+ "husky": "^8.0.1",
83
+ "jest": "^29.2.1",
84
+ "lint-staged": "^13.0.3",
85
+ "react": "^18.2.0",
86
+ "react-dom": "^18.2.0",
87
+ "redux-saga": "^1.2.1",
88
+ "rimraf": "^3.0.2",
89
+ "semantic-release": "^19.0.5",
90
+ "semantic-release-slack-bot": "^3.5.3",
91
+ "ts-jest": "^29.0.3",
92
+ "typescript": "^4.8.4"
93
+ },
94
+ "config": {
95
+ "commitizen": {
96
+ "path": "./node_modules/cz-conventional-changelog"
97
+ }
98
+ }
99
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * @Author: Erik Slovak <erik.slovak@technologystudio.sk>
3
+ * @Date: 2021-10-13T19:10:73+02:00
4
+ * @Copyright: Technology Studio
5
+ **/
6
+
7
+ export const serviceContext = (serviceName: string, serviceAttributes: Record<string, unknown>): string => (
8
+ `${serviceName}(${JSON.stringify(serviceAttributes)})`.replace(/\./g, '_')
9
+ )
@@ -0,0 +1,103 @@
1
+ /**
2
+ * @Author: Erik Slovak <erik.slovak@technologystudio.sk>
3
+ * @Date: 2022-03-17T14:03:65+01:00
4
+ * @Copyright: Technology Studio
5
+ **/
6
+
7
+ import type {
8
+ ServiceError,
9
+ } from '@txo/service-prop'
10
+ import { isObject } from '@txo/functional'
11
+ import set from 'lodash.set'
12
+
13
+ import type {
14
+ ErrorMap,
15
+ ErrorMapper,
16
+ } from '../Model/Types'
17
+ import {
18
+ VALIDATION_ERROR,
19
+ } from '../Model/Types'
20
+
21
+ const normaliseErrorMap = (errorMap: ErrorMap): ErrorMap => {
22
+ if (isObject(errorMap)) {
23
+ return Object.keys(errorMap).reduce((normalisedErrorMap: { [key: string]: ErrorMap }, key) => {
24
+ set(normalisedErrorMap, key, normaliseErrorMap(errorMap[key]))
25
+ return normalisedErrorMap
26
+ }, {})
27
+ }
28
+ return errorMap
29
+ }
30
+
31
+ export const ignoreError = (): ErrorMapper => () => undefined
32
+ export const validationError = (message?: string): ErrorMapper => ({
33
+ error,
34
+ }) => {
35
+ const nextError: ServiceError = {
36
+ ...error,
37
+ message: message ?? error.message,
38
+ meta: {
39
+ ...error.meta,
40
+ type: VALIDATION_ERROR,
41
+ },
42
+ }
43
+
44
+ return nextError
45
+ }
46
+
47
+ const getWithWildcardFallback = (errorMap: ErrorMap, path: string): ErrorMapper | undefined => {
48
+ if (errorMap === undefined) {
49
+ return undefined
50
+ }
51
+ if (path) {
52
+ if (isObject(errorMap)) {
53
+ const pathList = path.split('.')
54
+ const currentPath = pathList.shift()
55
+ const keyList = Object.keys(errorMap)
56
+ const currentKey = currentPath && keyList.includes(currentPath) ? currentPath : '*'
57
+ return getWithWildcardFallback(errorMap[currentKey], pathList.join('.'))
58
+ } else {
59
+ return undefined
60
+ }
61
+ }
62
+ return typeof errorMap === 'function' ? errorMap : undefined
63
+ }
64
+
65
+ export const applyErrorMap = (
66
+ serviceErrorList: ServiceError[],
67
+ errorMap: ErrorMap,
68
+ onFieldErrors?: (fieldErrors: Record<string, Record<string, string>>) => void,
69
+ ): ServiceError[] => {
70
+ const normalisedErrorMap = normaliseErrorMap(errorMap)
71
+ let modified = false
72
+ const fieldErrors = {}
73
+ const nextServiceErrorList = serviceErrorList
74
+ .reduce<ServiceError[]>(
75
+ (nextServiceErrorList, serviceError) => {
76
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
77
+ const graphQlError: any = serviceError.data
78
+ const path = [...(graphQlError?.path ?? []), serviceError.key].join('.')
79
+ const errorMapper = getWithWildcardFallback(normalisedErrorMap, path)
80
+
81
+ if (errorMapper) {
82
+ const nextServiceError = errorMapper({
83
+ error: serviceError,
84
+ fieldErrors,
85
+ path,
86
+ })
87
+ if (nextServiceError !== serviceError) {
88
+ modified = true
89
+ }
90
+ nextServiceError && nextServiceErrorList.push(nextServiceError)
91
+ } else {
92
+ nextServiceErrorList.push(serviceError)
93
+ }
94
+
95
+ return nextServiceErrorList
96
+ }, [])
97
+
98
+ if (onFieldErrors && Object.keys(fieldErrors).length > 0) {
99
+ onFieldErrors(fieldErrors)
100
+ }
101
+
102
+ return modified ? nextServiceErrorList : serviceErrorList
103
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * @Author: Erik Slovak <erik.slovak@technologystudio.sk>
3
+ * @Date: 2021-09-28T20:09:40+02:00
4
+ * @Copyright: Technology Studio
5
+ **/
6
+
7
+ import type {
8
+ DocumentNode,
9
+ OperationDefinitionNode,
10
+ } from 'graphql'
11
+
12
+ const upperCaseFirst = (str: string): string => str.charAt(0).toUpperCase() + str.slice(1)
13
+ const pascalCase = (string: string): string => (
14
+ `${string}`
15
+ .replace(/[-_]+/g, ' ')
16
+ .replace(/[^\w\s]/g, '')
17
+ .replace(
18
+ /\s+(.)(\w*)/g,
19
+ (_$1, $2: string, $3: string) => `${$2.toUpperCase() + $3.toLowerCase()}`,
20
+ )
21
+ .replace(/\w/, s => s.toUpperCase())
22
+ )
23
+
24
+ export const getName = (query: DocumentNode): string => {
25
+ const definition = query.definitions
26
+ .find(definition => (
27
+ definition.kind === 'OperationDefinition'
28
+ )) as OperationDefinitionNode
29
+ const operationName = definition?.name?.value
30
+ .split('_')
31
+ .map(pascalCase)
32
+ .join('.')
33
+ return operationName ?? upperCaseFirst(definition.operation)
34
+ }
@@ -0,0 +1,140 @@
1
+ /**
2
+ * @Author: Erik Slovak <erik.slovak@technologystudio.sk>
3
+ * @Date: 2021-08-24T13:08:91+02:00
4
+ * @Copyright: Technology Studio
5
+ **/
6
+
7
+ import type { DependencyList } from 'react'
8
+ import {
9
+ useCallback,
10
+ useContext,
11
+ useMemo,
12
+ useRef,
13
+ } from 'react'
14
+ import type {
15
+ CallAttributes,
16
+ ServiceProp,
17
+ ServiceErrorException,
18
+ } from '@txo/service-prop'
19
+ import { useMemoObject } from '@txo/hooks-react'
20
+ import type { Typify } from '@txo/types'
21
+ import type {
22
+ DocumentNode,
23
+ MutationOptions as ApolloMutationOptions,
24
+ TypedDocumentNode,
25
+ MutationResult,
26
+ MutationFunctionOptions as MutateFunctionOptions,
27
+ FetchResult,
28
+ } from '@apollo/client'
29
+ import {
30
+ useMutation,
31
+ } from '@apollo/client'
32
+ import { ErrorHandlerContext } from '@txo-peer-dep/service-error-handler-react'
33
+ import { operationPromiseProcessor } from '@txo/service-graphql'
34
+
35
+ import { serviceContext } from '../Api/ContextHelper'
36
+ import { getName } from '../Api/OperationHelper'
37
+ import type { ErrorMap } from '../Model/Types'
38
+ import { applyErrorMap } from '../Api/ErrorMapHelper'
39
+
40
+ const calculateContext = (mutation: DocumentNode, variables?: Record<string, unknown>): string => (
41
+ serviceContext(getName(mutation), variables ?? {})
42
+ )
43
+
44
+ export type MutationServiceProp<ATTRIBUTES, DATA, CALL_ATTRIBUTES extends CallAttributes<ATTRIBUTES>> =
45
+ Omit<ServiceProp<ATTRIBUTES, DATA, CALL_ATTRIBUTES, FetchResult<DATA>>, 'clear' | 'options' | 'clearException' | 'exception'>
46
+ & {
47
+ mutation: MutationResult<DATA>,
48
+ }
49
+
50
+ export type MutateFunction<DATA, ATTRIBUTES> = (options?: MutateFunctionOptions<DATA, ATTRIBUTES>) => Promise<FetchResult<DATA>>
51
+
52
+ export type MutationOptions<DATA, ATTRIBUTES> = {
53
+ onFieldErrors?: (fieldErrors: Record<string, Record<string, string>>) => void,
54
+ options?: Omit<ApolloMutationOptions<DATA, ATTRIBUTES>, 'mutation'>,
55
+ errorMap?: ErrorMap,
56
+ mutateFactory?: (mutate: MutateFunction<DATA, ATTRIBUTES>) => MutateFunction<DATA, ATTRIBUTES>,
57
+ onFieldErrorsDependencyList?: DependencyList,
58
+ errorMapDependencyList?: DependencyList,
59
+ }
60
+
61
+ export const useServiceMutation = <
62
+ ATTRIBUTES extends Record<string, unknown>,
63
+ DATA,
64
+ CALL_ATTRIBUTES extends CallAttributes<ATTRIBUTES>,
65
+ >(
66
+ mutationDocument: TypedDocumentNode<DATA, ATTRIBUTES>,
67
+ options?: MutationOptions<DATA, ATTRIBUTES>,
68
+ ): MutationServiceProp<ATTRIBUTES, DATA, CALL_ATTRIBUTES> => {
69
+ const {
70
+ onFieldErrors: defaultOnFieldErrors,
71
+ onFieldErrorsDependencyList,
72
+ errorMap,
73
+ errorMapDependencyList,
74
+ options: mutationOptions,
75
+ mutateFactory,
76
+ } = options ?? {}
77
+ const exceptionRef = useRef<ServiceErrorException | null>(null)
78
+ const memoizedErrorMap = useMemo(
79
+ () => errorMap,
80
+ // eslint-disable-next-line react-hooks/exhaustive-deps
81
+ errorMapDependencyList ?? [],
82
+ )
83
+ const memoizedDefaultOnFieldErrors = useMemo(
84
+ () => defaultOnFieldErrors,
85
+ // eslint-disable-next-line react-hooks/exhaustive-deps
86
+ onFieldErrorsDependencyList ?? [],
87
+ )
88
+ const [mutate, mutation] = useMutation<
89
+ DATA,
90
+ ATTRIBUTES
91
+ >(mutationDocument, mutationOptions)
92
+ const {
93
+ addServiceErrorException,
94
+ removeServiceErrorException,
95
+ } = useContext(ErrorHandlerContext)
96
+ const memoizedOptions = useMemoObject(mutationOptions as Omit<ApolloMutationOptions<DATA, ATTRIBUTES>, 'mutation'>)
97
+ const wrappedCall = useCallback(async (
98
+ variables: ATTRIBUTES,
99
+ callAttributes?: CALL_ATTRIBUTES,
100
+ ) => {
101
+ const attributes = { variables, mutation: mutationDocument, ...memoizedOptions }
102
+ const onFieldErrors = callAttributes?.onFieldErrors ?? memoizedDefaultOnFieldErrors
103
+ const context = calculateContext(mutationDocument, variables)
104
+ exceptionRef.current && removeServiceErrorException(context)
105
+ exceptionRef.current = null
106
+ const operationName = getName(mutationDocument)
107
+ const mutateWithErrorProcessor: typeof mutate = async (options) => (
108
+ operationPromiseProcessor(mutate(options), {
109
+ operationName,
110
+ context,
111
+ })
112
+ )
113
+ const nextMutate = mutateFactory?.(mutateWithErrorProcessor) ?? mutateWithErrorProcessor
114
+ return operationPromiseProcessor(nextMutate(attributes), {
115
+ operationName,
116
+ context,
117
+ })
118
+ .catch(async (serviceErrorException: ServiceErrorException) => {
119
+ if (memoizedErrorMap) {
120
+ serviceErrorException.serviceErrorList = applyErrorMap(
121
+ serviceErrorException.serviceErrorList,
122
+ memoizedErrorMap,
123
+ onFieldErrors,
124
+ )
125
+ }
126
+ addServiceErrorException(serviceErrorException)
127
+ exceptionRef.current = serviceErrorException
128
+ throw serviceErrorException
129
+ })
130
+ }, [mutationDocument, memoizedOptions, memoizedDefaultOnFieldErrors, removeServiceErrorException, mutateFactory, mutate, memoizedErrorMap, addServiceErrorException])
131
+
132
+ const memoizedMutation = useMemoObject<Typify<MutationResult<DATA>>>(mutation)
133
+
134
+ return useMemo(() => ({
135
+ mutation: memoizedMutation,
136
+ data: memoizedMutation.data ?? null,
137
+ fetching: memoizedMutation.loading,
138
+ call: wrappedCall,
139
+ }), [memoizedMutation, wrappedCall])
140
+ }
@@ -0,0 +1,126 @@
1
+ /**
2
+ * @Author: Erik Slovak <erik.slovak@technologystudio.sk>
3
+ * @Date: 2021-09-01T16:09:57+02:00
4
+ * @Copyright: Technology Studio
5
+ **/
6
+
7
+ import {
8
+ useContext,
9
+ useLayoutEffect,
10
+ useMemo,
11
+ useRef,
12
+ } from 'react'
13
+ import type {
14
+ DocumentNode,
15
+ QueryHookOptions,
16
+ TypedDocumentNode,
17
+ QueryResult,
18
+ } from '@apollo/client'
19
+ import {
20
+ useQuery,
21
+ } from '@apollo/client'
22
+ import get from 'lodash.get'
23
+ import type { Get } from 'type-fest'
24
+ import type {
25
+ CallAttributes,
26
+ ServiceError,
27
+ ServiceProp,
28
+ } from '@txo/service-prop'
29
+ import {
30
+ ServiceErrorException,
31
+ } from '@txo/service-prop'
32
+ import { configManager } from '@txo-peer-dep/service-graphql'
33
+ import {
34
+ useMemoObject,
35
+ } from '@txo/hooks-react'
36
+ import { ErrorHandlerContext } from '@txo-peer-dep/service-error-handler-react'
37
+ import type { Typify } from '@txo/types'
38
+
39
+ import { serviceContext } from '../Api/ContextHelper'
40
+ import { getName } from '../Api/OperationHelper'
41
+
42
+ const calculateContext = (query: DocumentNode, variables: Record<string, unknown> | undefined): string => (
43
+ serviceContext(getName(query), variables ?? {})
44
+ )
45
+
46
+ export type QueryServiceProp<ATTRIBUTES, DATA, MAPPED_DATA, CALL_ATTRIBUTES extends CallAttributes<ATTRIBUTES>> =
47
+ Omit<ServiceProp<ATTRIBUTES, MAPPED_DATA, CALL_ATTRIBUTES>, 'call' | 'clear' | 'options' | 'clearException'>
48
+ & {
49
+ query: QueryResult<DATA, ATTRIBUTES>,
50
+ }
51
+
52
+ type QueryOptions<DATA, ATTRIBUTES, DATA_PATH extends string> = {
53
+ options?: QueryHookOptions<DATA, ATTRIBUTES>,
54
+ dataPath: DATA_PATH,
55
+ }
56
+
57
+ const isServiceErrorListEqual = (a: ServiceError[], b: ServiceError[]): boolean => {
58
+ if (a.length !== b.length) {
59
+ return false
60
+ }
61
+ if (a.every((error, index) => (b[index].key === error.key) && (b[index].message === error.message))) {
62
+ return true
63
+ }
64
+ return false
65
+ }
66
+
67
+ // TODO: find a better way to parse type of dataPath (from attribute)
68
+ export const useServiceQuery = <
69
+ ATTRIBUTES extends Record<string, unknown>,
70
+ DATA,
71
+ CALL_ATTRIBUTES extends CallAttributes<ATTRIBUTES>,
72
+ DATA_PATH extends string
73
+ >(
74
+ queryDocument: TypedDocumentNode<DATA, ATTRIBUTES>,
75
+ options: QueryOptions<DATA, ATTRIBUTES, DATA_PATH>,
76
+ ): QueryServiceProp<ATTRIBUTES, DATA, Get<DATA, DATA_PATH>, CALL_ATTRIBUTES> => {
77
+ const {
78
+ dataPath,
79
+ options: queryOptions,
80
+ } = options
81
+ const query: QueryResult<DATA, ATTRIBUTES> = useQuery<DATA, ATTRIBUTES>(queryDocument, queryOptions)
82
+ const shownExceptionListRef = useRef<(ServiceErrorException)[]>([])
83
+ const {
84
+ addServiceErrorException,
85
+ removeServiceErrorException,
86
+ } = useContext(ErrorHandlerContext)
87
+ const memoizedVariables = useMemoObject(queryOptions?.variables)
88
+ const memoizedQuery = useMemoObject<Typify<QueryResult<DATA, ATTRIBUTES>>>(query)
89
+ const context = useMemo(() => (
90
+ calculateContext(queryDocument, memoizedVariables)
91
+ ), [queryDocument, memoizedVariables])
92
+ const exception = useMemo(() => {
93
+ const operationName = getName(queryDocument)
94
+ if (memoizedQuery.error) {
95
+ const errorList = configManager.config.errorResponseTranslator(memoizedQuery.error, {
96
+ context,
97
+ operationName,
98
+ })
99
+ const exception = new ServiceErrorException({
100
+ serviceErrorList: errorList,
101
+ serviceName: operationName,
102
+ context,
103
+ })
104
+ return exception
105
+ }
106
+ return null
107
+ }, [context, memoizedQuery, queryDocument])
108
+ useLayoutEffect(() => {
109
+ if (exception && !shownExceptionListRef.current.find(shownException => (
110
+ isServiceErrorListEqual(shownException.serviceErrorList, exception.serviceErrorList)
111
+ ))) {
112
+ addServiceErrorException(exception)
113
+ shownExceptionListRef.current.push(exception)
114
+ }
115
+ return () => {
116
+ exception && removeServiceErrorException(context)
117
+ }
118
+ }, [addServiceErrorException, context, exception, memoizedVariables, queryDocument, removeServiceErrorException])
119
+
120
+ return useMemo(() => ({
121
+ query: memoizedQuery,
122
+ data: get(memoizedQuery.data, dataPath),
123
+ fetching: memoizedQuery.loading,
124
+ exception,
125
+ }), [memoizedQuery, exception, dataPath])
126
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * @Author: Erik Slovak <erik.slovak@technologystudio.sk>
3
+ * @Date: 2022-03-17T10:03:96+01:00
4
+ * @Copyright: Technology Studio
5
+ **/
6
+
7
+ import type { ServiceError } from '@txo/service-prop'
8
+
9
+ export type ErrorMapper = ((options: {
10
+ error: ServiceError,
11
+ fieldErrors?: Record<string, Record<string, string>>,
12
+ path: string,
13
+ }) => ServiceError | undefined) | undefined
14
+
15
+ export type ErrorMap = { [key: string]: ErrorMap } | ErrorMapper
16
+
17
+ export const VALIDATION_ERROR = 'VALIDATION_ERROR'
package/src/index.ts ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * @Author: Erik Slovak <erik.slovak@technologystudio.sk>
3
+ * @Date: 2022-01-24T13:01:19+01:00
4
+ * @Copyright: Technology Studio
5
+ **/
6
+
7
+ export { getName } from './Api/OperationHelper'
8
+ export * from './Api/ErrorMapHelper'
9
+ export * from './Hooks/UseServiceMutation'
10
+ export {
11
+ useServiceQuery,
12
+ QueryServiceProp,
13
+ } from './Hooks/UseServiceQuery'
14
+ export * from './Model/Types'