@astral/mobx-query 1.8.0 → 1.9.0

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.
Files changed (98) hide show
  1. package/MobxQuery/MobxQuery.d.ts +44 -0
  2. package/MobxQuery/MobxQuery.js +48 -0
  3. package/README.md +1048 -287
  4. package/Sets/InfiniteQuerySet/InfiniteQuerySet.d.ts +60 -0
  5. package/Sets/InfiniteQuerySet/InfiniteQuerySet.js +71 -0
  6. package/Sets/InfiniteQuerySet/index.d.ts +1 -0
  7. package/Sets/InfiniteQuerySet/index.js +1 -0
  8. package/Sets/MutationSet/MutationSet.d.ts +32 -0
  9. package/Sets/MutationSet/MutationSet.js +31 -0
  10. package/Sets/MutationSet/index.d.ts +1 -0
  11. package/Sets/MutationSet/index.js +1 -0
  12. package/Sets/QuerySet/QuerySet.d.ts +64 -0
  13. package/Sets/QuerySet/QuerySet.js +72 -0
  14. package/Sets/QuerySet/index.d.ts +1 -0
  15. package/Sets/QuerySet/index.js +1 -0
  16. package/Sets/index.d.ts +3 -0
  17. package/Sets/index.js +3 -0
  18. package/Sets/utils/generateQuerySetBaseKey/generateQuerySetBaseKey.d.ts +4 -0
  19. package/Sets/utils/generateQuerySetBaseKey/generateQuerySetBaseKey.js +5 -0
  20. package/Sets/utils/generateQuerySetBaseKey/index.d.ts +1 -0
  21. package/Sets/utils/generateQuerySetBaseKey/index.js +1 -0
  22. package/Sets/utils/generateQuerySetKeys/generateQuerySetKeys.d.ts +9 -0
  23. package/Sets/utils/generateQuerySetKeys/generateQuerySetKeys.js +20 -0
  24. package/Sets/utils/generateQuerySetKeys/index.d.ts +1 -0
  25. package/Sets/utils/generateQuerySetKeys/index.js +1 -0
  26. package/Sets/utils/index.d.ts +2 -0
  27. package/Sets/utils/index.js +2 -0
  28. package/index.d.ts +2 -1
  29. package/index.js +1 -0
  30. package/node/AdaptableMap/AdaptableMap.d.ts +29 -0
  31. package/node/AdaptableMap/AdaptableMap.js +81 -0
  32. package/node/AdaptableMap/index.d.ts +1 -0
  33. package/node/AdaptableMap/index.js +17 -0
  34. package/node/AuxiliaryQuery/AuxiliaryQuery.d.ts +55 -0
  35. package/node/AuxiliaryQuery/AuxiliaryQuery.js +115 -0
  36. package/node/AuxiliaryQuery/index.d.ts +1 -0
  37. package/node/AuxiliaryQuery/index.js +17 -0
  38. package/node/DataStorage/DataStorage.d.ts +33 -0
  39. package/node/DataStorage/DataStorage.js +51 -0
  40. package/node/DataStorage/index.d.ts +1 -0
  41. package/node/DataStorage/index.js +17 -0
  42. package/node/InfiniteQuery/InfiniteQuery.d.ts +135 -0
  43. package/node/InfiniteQuery/InfiniteQuery.js +169 -0
  44. package/node/InfiniteQuery/index.d.ts +1 -0
  45. package/node/InfiniteQuery/index.js +17 -0
  46. package/node/MobxQuery/MobxQuery.d.ts +176 -0
  47. package/node/MobxQuery/MobxQuery.js +225 -0
  48. package/node/MobxQuery/index.d.ts +1 -0
  49. package/node/MobxQuery/index.js +17 -0
  50. package/node/Mutation/Mutation.d.ts +34 -0
  51. package/node/Mutation/Mutation.js +47 -0
  52. package/node/Mutation/index.d.ts +1 -0
  53. package/node/Mutation/index.js +17 -0
  54. package/node/Query/Query.d.ts +103 -0
  55. package/node/Query/Query.js +113 -0
  56. package/node/Query/index.d.ts +1 -0
  57. package/node/Query/index.js +17 -0
  58. package/node/QueryContainer/QueryContainer.d.ts +61 -0
  59. package/node/QueryContainer/QueryContainer.js +83 -0
  60. package/node/QueryContainer/index.d.ts +1 -0
  61. package/node/QueryContainer/index.js +17 -0
  62. package/node/Sets/InfiniteQuerySet/InfiniteQuerySet.d.ts +60 -0
  63. package/node/Sets/InfiniteQuerySet/InfiniteQuerySet.js +75 -0
  64. package/node/Sets/InfiniteQuerySet/index.d.ts +1 -0
  65. package/node/Sets/InfiniteQuerySet/index.js +17 -0
  66. package/node/Sets/MutationSet/MutationSet.d.ts +32 -0
  67. package/node/Sets/MutationSet/MutationSet.js +35 -0
  68. package/node/Sets/MutationSet/index.d.ts +1 -0
  69. package/node/Sets/MutationSet/index.js +17 -0
  70. package/node/Sets/QuerySet/QuerySet.d.ts +64 -0
  71. package/node/Sets/QuerySet/QuerySet.js +76 -0
  72. package/node/Sets/QuerySet/index.d.ts +1 -0
  73. package/node/Sets/QuerySet/index.js +17 -0
  74. package/node/Sets/index.d.ts +3 -0
  75. package/node/Sets/index.js +19 -0
  76. package/node/Sets/utils/generateQuerySetBaseKey/generateQuerySetBaseKey.d.ts +4 -0
  77. package/node/Sets/utils/generateQuerySetBaseKey/generateQuerySetBaseKey.js +12 -0
  78. package/node/Sets/utils/generateQuerySetBaseKey/index.d.ts +1 -0
  79. package/node/Sets/utils/generateQuerySetBaseKey/index.js +17 -0
  80. package/node/Sets/utils/generateQuerySetKeys/generateQuerySetKeys.d.ts +9 -0
  81. package/node/Sets/utils/generateQuerySetKeys/generateQuerySetKeys.js +27 -0
  82. package/node/Sets/utils/generateQuerySetKeys/index.d.ts +1 -0
  83. package/node/Sets/utils/generateQuerySetKeys/index.js +17 -0
  84. package/node/Sets/utils/index.d.ts +2 -0
  85. package/node/Sets/utils/index.js +18 -0
  86. package/node/StatusStorage/StatusStorage.d.ts +24 -0
  87. package/node/StatusStorage/StatusStorage.js +41 -0
  88. package/node/StatusStorage/index.d.ts +1 -0
  89. package/node/StatusStorage/index.js +17 -0
  90. package/node/StorageFactory/StorageFactory.d.ts +9 -0
  91. package/node/StorageFactory/StorageFactory.js +23 -0
  92. package/node/StorageFactory/index.d.ts +1 -0
  93. package/node/StorageFactory/index.js +17 -0
  94. package/node/index.d.ts +6 -0
  95. package/node/index.js +11 -0
  96. package/node/types.d.ts +55 -0
  97. package/node/types.js +2 -0
  98. package/package.json +11 -4
@@ -0,0 +1,113 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Query = void 0;
4
+ const mobx_1 = require("mobx");
5
+ const AuxiliaryQuery_1 = require("../AuxiliaryQuery");
6
+ const QueryContainer_1 = require("../QueryContainer");
7
+ /**
8
+ * Стор для работы с запросами,
9
+ * которые должны быть закешированы,
10
+ * но им не требуется усложнение в виде работы с фильтрами и инфинити запросами
11
+ */
12
+ class Query extends QueryContainer_1.QueryContainer {
13
+ constructor(executor, { onError, enabledAutoFetch, fetchPolicy, dataStorage, statusStorage, backgroundStatusStorage = null, submitValidity, }) {
14
+ super(statusStorage, backgroundStatusStorage, new AuxiliaryQuery_1.AuxiliaryQuery(statusStorage, backgroundStatusStorage));
15
+ this.executor = executor;
16
+ /**
17
+ * Метод для инвалидации данных
18
+ */
19
+ this.invalidate = () => {
20
+ this.auxiliary.invalidate();
21
+ };
22
+ /**
23
+ * Синхронный метод получения данных
24
+ */
25
+ this.sync = (params) => {
26
+ const isInstanceAllow = !(this.isLoading || this.isSuccess);
27
+ if (this.isNetworkOnly || this.auxiliary.isInvalid || isInstanceAllow) {
28
+ this.proceedSync(params);
29
+ }
30
+ };
31
+ /**
32
+ * Обработчик успешного ответа
33
+ */
34
+ this.submitSuccess = (resData) => {
35
+ var _a;
36
+ this.storage.setData(resData);
37
+ (_a = this.submitValidity) === null || _a === void 0 ? void 0 : _a.call(this);
38
+ return resData;
39
+ };
40
+ /**
41
+ * Форс метод для установки данных
42
+ */
43
+ this.forceUpdate = (data) => {
44
+ this.auxiliary.submitSuccess();
45
+ this.submitSuccess(data);
46
+ };
47
+ /**
48
+ * Метод для переиспользования синхронной логики запроса
49
+ */
50
+ this.proceedSync = (options) => {
51
+ const { onSuccess, onError } = options || {};
52
+ this.auxiliary
53
+ .getUnifiedPromise(this.executor, (res) => {
54
+ this.submitSuccess(res);
55
+ onSuccess === null || onSuccess === void 0 ? void 0 : onSuccess(res);
56
+ })
57
+ .catch((e) => {
58
+ var _a;
59
+ if (onError) {
60
+ onError(e);
61
+ }
62
+ else {
63
+ (_a = this.defaultOnError) === null || _a === void 0 ? void 0 : _a.call(this, e);
64
+ }
65
+ });
66
+ };
67
+ /**
68
+ * Асинхронный метод получения данных,
69
+ * предполагается, что нужно будет самостоятельно обрабатывать ошибку
70
+ */
71
+ this.async = () => {
72
+ if (!this.isNetworkOnly && this.isSuccess && !this.auxiliary.isInvalid) {
73
+ return Promise.resolve(this.storage.data);
74
+ }
75
+ return this.auxiliary.getUnifiedPromise(this.executor, this.submitSuccess);
76
+ };
77
+ this.defaultOnError = onError;
78
+ this.enabledAutoFetch = enabledAutoFetch;
79
+ this.defaultFetchPolicy = fetchPolicy;
80
+ this.storage = dataStorage;
81
+ this.submitValidity = submitValidity;
82
+ (0, mobx_1.makeObservable)(this, {
83
+ async: mobx_1.action,
84
+ sync: mobx_1.action,
85
+ forceUpdate: mobx_1.action,
86
+ data: mobx_1.computed,
87
+ submitSuccess: mobx_1.action,
88
+ });
89
+ }
90
+ get isNetworkOnly() {
91
+ return this.defaultFetchPolicy === 'network-only';
92
+ }
93
+ /**
94
+ * Содержит реактивные данные
95
+ * благодаря mobx, при изменении isInvalid, свойство будет вычисляться заново,
96
+ * следовательно, стриггерится условие невалидности,
97
+ * и начнется запрос, в результате которого, данные обновятся
98
+ */
99
+ get data() {
100
+ const shouldSync = this.enabledAutoFetch &&
101
+ !this.isSuccess &&
102
+ !this.isLoading &&
103
+ !this.isError;
104
+ if (this.auxiliary.isInvalid || shouldSync) {
105
+ // т.к. при вызове апдейта, изменяются флаги, на которые подписан data,
106
+ // нужно вызывать этот экшн асинхронно
107
+ (0, mobx_1.when)(() => true, this.proceedSync);
108
+ }
109
+ // возвращаем имеющиеся данные
110
+ return this.storage.data;
111
+ }
112
+ }
113
+ exports.Query = Query;
@@ -0,0 +1 @@
1
+ export * from './Query';
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./Query"), exports);
@@ -0,0 +1,61 @@
1
+ import { type StatusStorage } from '../StatusStorage';
2
+ export type QueryContainerAuxiliary = {
3
+ isIdle: boolean;
4
+ };
5
+ type Statuses<TError> = StatusStorage<TError>;
6
+ /**
7
+ * Контейнер для бойлерплейт части,
8
+ * позволяет не повторять в каждом наследуемом классе использование стандартных статусов
9
+ */
10
+ export declare abstract class QueryContainer<TError, TAuxiliary extends QueryContainerAuxiliary, TIsBackground extends boolean> implements Statuses<TError> {
11
+ private readonly statusStorage;
12
+ private readonly backgroundStatusStorage;
13
+ protected readonly auxiliary: TAuxiliary;
14
+ protected constructor(statusStorage: StatusStorage<TError>, backgroundStatusStorage: StatusStorage<TError> | null, auxiliary: TAuxiliary);
15
+ /**
16
+ * Флаг загрузки данных
17
+ */
18
+ get isLoading(): boolean;
19
+ /**
20
+ * Флаг обозначающий, что последний запрос был зафейлен
21
+ */
22
+ get isError(): boolean;
23
+ /**
24
+ * Данные о последней ошибке
25
+ */
26
+ get error(): TError | undefined;
27
+ /**
28
+ * Флаг обозначающий, что последний запрос был успешно завершен
29
+ */
30
+ get isSuccess(): boolean;
31
+ /**
32
+ * Флаг, обозначающий простаивание, т.е. запроса еще не было
33
+ */
34
+ get isIdle(): boolean;
35
+ /**
36
+ * Статусы, изменяющиеся после первого успешного запроса в режиме isBackground: true
37
+ * @example
38
+ * const query = mobxQuery.createQuery(
39
+ * ['some cache key'],
40
+ * () => Promise.resolve('foo'),
41
+ * { isBackground: true }
42
+ * );
43
+ *
44
+ * await query.async();
45
+ * console.log(query.isLoading); // переключался в true на момент запроса
46
+ * console.log(query.isSuccess); // true
47
+ *
48
+ * query.invalidate();
49
+ * await query.async();
50
+ * console.log(query.isLoading); // не изменялся
51
+ * console.log(query.isSuccess); // остался неизменным - true
52
+ *
53
+ * console.log(query.background.isLoading); // переключался в true на момент обновления
54
+ * console.log(query.background.isSuccess); // true
55
+ *
56
+ * @exception isBackground:false (а так же по умолчанию) background не доступен, и равен null
57
+ * @exception Mutation не доступен в мутации и равен null
58
+ */
59
+ get background(): TIsBackground extends true ? Statuses<TError> : null;
60
+ }
61
+ export {};
@@ -0,0 +1,83 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.QueryContainer = void 0;
4
+ const mobx_1 = require("mobx");
5
+ /**
6
+ * Контейнер для бойлерплейт части,
7
+ * позволяет не повторять в каждом наследуемом классе использование стандартных статусов
8
+ */
9
+ class QueryContainer {
10
+ constructor(statusStorage, backgroundStatusStorage, auxiliary) {
11
+ this.statusStorage = statusStorage;
12
+ this.backgroundStatusStorage = backgroundStatusStorage;
13
+ this.auxiliary = auxiliary;
14
+ (0, mobx_1.makeObservable)(this, {
15
+ error: mobx_1.computed,
16
+ isError: mobx_1.computed,
17
+ isIdle: mobx_1.computed,
18
+ isLoading: mobx_1.computed,
19
+ isSuccess: mobx_1.computed,
20
+ });
21
+ }
22
+ /**
23
+ * Флаг загрузки данных
24
+ */
25
+ get isLoading() {
26
+ return this.statusStorage.isLoading;
27
+ }
28
+ /**
29
+ * Флаг обозначающий, что последний запрос был зафейлен
30
+ */
31
+ get isError() {
32
+ return this.statusStorage.isError;
33
+ }
34
+ /**
35
+ * Данные о последней ошибке
36
+ */
37
+ get error() {
38
+ return this.statusStorage.error;
39
+ }
40
+ /**
41
+ * Флаг обозначающий, что последний запрос был успешно завершен
42
+ */
43
+ get isSuccess() {
44
+ return this.statusStorage.isSuccess;
45
+ }
46
+ /**
47
+ * Флаг, обозначающий простаивание, т.е. запроса еще не было
48
+ */
49
+ get isIdle() {
50
+ return this.auxiliary.isIdle;
51
+ }
52
+ /**
53
+ * Статусы, изменяющиеся после первого успешного запроса в режиме isBackground: true
54
+ * @example
55
+ * const query = mobxQuery.createQuery(
56
+ * ['some cache key'],
57
+ * () => Promise.resolve('foo'),
58
+ * { isBackground: true }
59
+ * );
60
+ *
61
+ * await query.async();
62
+ * console.log(query.isLoading); // переключался в true на момент запроса
63
+ * console.log(query.isSuccess); // true
64
+ *
65
+ * query.invalidate();
66
+ * await query.async();
67
+ * console.log(query.isLoading); // не изменялся
68
+ * console.log(query.isSuccess); // остался неизменным - true
69
+ *
70
+ * console.log(query.background.isLoading); // переключался в true на момент обновления
71
+ * console.log(query.background.isSuccess); // true
72
+ *
73
+ * @exception isBackground:false (а так же по умолчанию) background не доступен, и равен null
74
+ * @exception Mutation не доступен в мутации и равен null
75
+ */
76
+ get background() {
77
+ if (!this.backgroundStatusStorage) {
78
+ return null;
79
+ }
80
+ return this.backgroundStatusStorage;
81
+ }
82
+ }
83
+ exports.QueryContainer = QueryContainer;
@@ -0,0 +1 @@
1
+ export * from './QueryContainer';
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./QueryContainer"), exports);
@@ -0,0 +1,60 @@
1
+ import { type DeepPartial } from 'utility-types';
2
+ import { type CacheKey } from '../../types';
3
+ import { type InfiniteParams, type InfiniteQuery } from '../../InfiniteQuery';
4
+ import { type CreateInfiniteQueryParams, type MobxQuery } from '../../MobxQuery';
5
+ export type InfiniteQuerySetConfig = {
6
+ name?: string;
7
+ };
8
+ export type InfiniteQuerySetConfigurator<TParams extends any[], TResponse> = (...params: TParams) => {
9
+ keys?: CacheKey[];
10
+ execute: (infiniteParams: InfiniteParams) => Promise<TResponse[]>;
11
+ };
12
+ /**
13
+ * Набор infinite queries под одним ключем с целью повышения читаемости кода и удобства инвалидации по общему ключу
14
+ */
15
+ export declare class InfiniteQuerySet<TParams extends any[], TResponse, TDefaultError = unknown> {
16
+ private readonly _cache;
17
+ private readonly _queryConfigurator;
18
+ private readonly baseKey;
19
+ constructor(_cache: MobxQuery, _queryConfigurator: InfiniteQuerySetConfigurator<TParams, TResponse>, config?: InfiniteQuerySetConfig);
20
+ /**
21
+ * Создает infinite query в кэше. Добавляет его в набор
22
+ * @returns InfiniteQuery объект
23
+ * @example
24
+ * const docListQuery = docFetcher.infiniteQueries.docList.create()
25
+ * // Получает данные
26
+ * docListQuery.sync()
27
+ */
28
+ create: <TError = TDefaultError>(...params: TParams) => InfiniteQuery<TResponse, TError>;
29
+ /**
30
+ * Создает infinite query в кэше с дополнительными параметрами конфигурации. Добавляет его в набор
31
+ * @param config - Параметры конфигурации infinite query. Например, fetchPolicy или incrementCount
32
+ * @param params - Параметры запроса
33
+ * @returns InfiniteQuery объект
34
+ * @example
35
+ * const docListQuery = docFetcher.infiniteQueries.docList.createWithConfig(
36
+ * { fetchPolicy: 'network-only', incrementCount: 10 },
37
+ * 'docId',
38
+ * )
39
+ * // Получает данные из query
40
+ * docListQuery.sync()
41
+ */
42
+ createWithConfig: <TError = TDefaultError, TIsBackground extends boolean = false>(config: CreateInfiniteQueryParams<TResponse, TError, TIsBackground>, ...params: TParams) => InfiniteQuery<TResponse, TError, TIsBackground>;
43
+ /**
44
+ * Инвалидирует текущий набор infinite queries в кэше
45
+ * @param params - Параметры функции, переданной в createInfiniteQuerySet при создании набора. Если не указаны, то инвалидируется все query
46
+ * @example
47
+ * const docFetcher = {
48
+ * infiniteQueries: {
49
+ * docList: createInfiniteQuerySet('docList', (search: string) => ({
50
+ * execute: ({ count, offset }) => httpService.get(`/doc/${search}?count=${count}&offset=${offset}`),
51
+ * }),
52
+ * }
53
+ * };
54
+ *
55
+ * // Инвалидирует infinite query с конкретным переданным search
56
+ * docFetcher.infiniteQueries.docList.invalidate('документ1')
57
+ */
58
+ invalidate: (...params: DeepPartial<TParams>) => void;
59
+ private configureQuery;
60
+ }
@@ -0,0 +1,75 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.InfiniteQuerySet = void 0;
4
+ const utils_1 = require("../utils");
5
+ /**
6
+ * Набор infinite queries под одним ключем с целью повышения читаемости кода и удобства инвалидации по общему ключу
7
+ */
8
+ class InfiniteQuerySet {
9
+ constructor(_cache, _queryConfigurator, config) {
10
+ var _a;
11
+ this._cache = _cache;
12
+ this._queryConfigurator = _queryConfigurator;
13
+ /**
14
+ * Создает infinite query в кэше. Добавляет его в набор
15
+ * @returns InfiniteQuery объект
16
+ * @example
17
+ * const docListQuery = docFetcher.infiniteQueries.docList.create()
18
+ * // Получает данные
19
+ * docListQuery.sync()
20
+ */
21
+ this.create = (...params) => {
22
+ const { keys, execute } = this.configureQuery(...params);
23
+ return this._cache.createInfiniteQuery(keys, execute);
24
+ };
25
+ /**
26
+ * Создает infinite query в кэше с дополнительными параметрами конфигурации. Добавляет его в набор
27
+ * @param config - Параметры конфигурации infinite query. Например, fetchPolicy или incrementCount
28
+ * @param params - Параметры запроса
29
+ * @returns InfiniteQuery объект
30
+ * @example
31
+ * const docListQuery = docFetcher.infiniteQueries.docList.createWithConfig(
32
+ * { fetchPolicy: 'network-only', incrementCount: 10 },
33
+ * 'docId',
34
+ * )
35
+ * // Получает данные из query
36
+ * docListQuery.sync()
37
+ */
38
+ this.createWithConfig = (config, ...params) => {
39
+ const { keys, execute } = this.configureQuery(...params);
40
+ return this._cache.createInfiniteQuery(keys, execute, config);
41
+ };
42
+ /**
43
+ * Инвалидирует текущий набор infinite queries в кэше
44
+ * @param params - Параметры функции, переданной в createInfiniteQuerySet при создании набора. Если не указаны, то инвалидируется все query
45
+ * @example
46
+ * const docFetcher = {
47
+ * infiniteQueries: {
48
+ * docList: createInfiniteQuerySet('docList', (search: string) => ({
49
+ * execute: ({ count, offset }) => httpService.get(`/doc/${search}?count=${count}&offset=${offset}`),
50
+ * }),
51
+ * }
52
+ * };
53
+ *
54
+ * // Инвалидирует infinite query с конкретным переданным search
55
+ * docFetcher.infiniteQueries.docList.invalidate('документ1')
56
+ */
57
+ this.invalidate = (...params) => {
58
+ if (params.length === 0) {
59
+ this._cache.invalidate([this.baseKey]);
60
+ return;
61
+ }
62
+ const { keys } = this.configureQuery(...params);
63
+ this._cache.invalidate(keys, 'chain-match');
64
+ };
65
+ this.configureQuery = (...params) => {
66
+ const { keys, execute } = this._queryConfigurator(...params);
67
+ return {
68
+ keys: (0, utils_1.generateQuerySetKeys)(this.baseKey, keys !== null && keys !== void 0 ? keys : params),
69
+ execute,
70
+ };
71
+ };
72
+ this.baseKey = (_a = config === null || config === void 0 ? void 0 : config.name) !== null && _a !== void 0 ? _a : (0, utils_1.generateQuerySetBaseKey)(_queryConfigurator);
73
+ }
74
+ }
75
+ exports.InfiniteQuerySet = InfiniteQuerySet;
@@ -0,0 +1 @@
1
+ export * from './InfiniteQuerySet';
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./InfiniteQuerySet"), exports);
@@ -0,0 +1,32 @@
1
+ import { type MobxQuery } from '../../MobxQuery';
2
+ import { type Mutation, type MutationExecutor } from '../../Mutation';
3
+ /**
4
+ * Налор мутаций. Цель: единый интерфейс создания и использования наборов Query и Mutation
5
+ * @example
6
+ * const docFetcher = {
7
+ * mutations: {
8
+ * editDoc: mobxQuery.createMutationSet((params: DocsEndpointsDTO.EditDocInput) => {
9
+ * return docsEndpoint.editDoc(params);
10
+ * }),
11
+ * },
12
+ * queries: {
13
+ * doc: mobxQuery.createQuerySet((id: string) => ({
14
+ * execute: () => docsEndpoint.getDoc(id).then(({ data }) => data),
15
+ * })),
16
+ * },
17
+ * }
18
+ */
19
+ export declare class MutationSet<TResponse, TParams = void, TDefaultError = unknown> {
20
+ private readonly _cache;
21
+ private readonly _executor;
22
+ constructor(_cache: MobxQuery, _executor: MutationExecutor<TResponse, TParams>);
23
+ /**
24
+ * Создает мутацию
25
+ * @returns Mutation объект
26
+ * @example
27
+ * const editDocMutation = docFetcher.mutations.editDoc.create();
28
+ * // Выполняет мутацию
29
+ * editDocMutation.sync({ params: { id: 'docId', content: 'Новое содержимое' } });
30
+ */
31
+ create: <TError = TDefaultError>() => Mutation<TResponse, TError, TParams>;
32
+ }
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MutationSet = void 0;
4
+ /**
5
+ * Налор мутаций. Цель: единый интерфейс создания и использования наборов Query и Mutation
6
+ * @example
7
+ * const docFetcher = {
8
+ * mutations: {
9
+ * editDoc: mobxQuery.createMutationSet((params: DocsEndpointsDTO.EditDocInput) => {
10
+ * return docsEndpoint.editDoc(params);
11
+ * }),
12
+ * },
13
+ * queries: {
14
+ * doc: mobxQuery.createQuerySet((id: string) => ({
15
+ * execute: () => docsEndpoint.getDoc(id).then(({ data }) => data),
16
+ * })),
17
+ * },
18
+ * }
19
+ */
20
+ class MutationSet {
21
+ constructor(_cache, _executor) {
22
+ this._cache = _cache;
23
+ this._executor = _executor;
24
+ /**
25
+ * Создает мутацию
26
+ * @returns Mutation объект
27
+ * @example
28
+ * const editDocMutation = docFetcher.mutations.editDoc.create();
29
+ * // Выполняет мутацию
30
+ * editDocMutation.sync({ params: { id: 'docId', content: 'Новое содержимое' } });
31
+ */
32
+ this.create = () => this._cache.createMutation(this._executor);
33
+ }
34
+ }
35
+ exports.MutationSet = MutationSet;
@@ -0,0 +1 @@
1
+ export * from './MutationSet';
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./MutationSet"), exports);
@@ -0,0 +1,64 @@
1
+ import { type DeepPartial } from 'utility-types';
2
+ import { type CacheKey } from '../../types';
3
+ import { type Query } from '../../Query';
4
+ import { type CreateQueryParams, type MobxQuery } from '../../MobxQuery';
5
+ export type QuerySetConfig = {
6
+ name?: string;
7
+ };
8
+ export type QuerySetConfigurator<TParams extends any[], TResponse> = (...params: TParams) => {
9
+ keys?: CacheKey[];
10
+ execute: () => Promise<TResponse>;
11
+ };
12
+ /**
13
+ * Набор queries под одним ключем с целью повышения читаемости кода и удобства инвалидации по общему ключу
14
+ */
15
+ export declare class QuerySet<TParams extends any[], TResponse, TDefaultError = unknown> {
16
+ private readonly _cache;
17
+ private readonly _queryConfigurator;
18
+ /**
19
+ * Хэш от queryConfigurator
20
+ */
21
+ private readonly baseKey;
22
+ constructor(_cache: MobxQuery, _queryConfigurator: QuerySetConfigurator<TParams, TResponse>, config?: QuerySetConfig);
23
+ /**
24
+ * Создает query в кэше. Добавляет его в набор
25
+ * @returns Query объект
26
+ * @example
27
+ * const docQuery = docFetcher.queries.doc.create('docId')
28
+ * // Получает данные
29
+ * docQuery.sync()
30
+ */
31
+ create: <TError = TDefaultError>(...params: TParams) => Query<TResponse, TError>;
32
+ /**
33
+ * Создает query в кэше с дополнительными параметрами конфигурации. Добавляет его в набор
34
+ * @param config - Параметры конфигурации query. Например, fetchPolicy
35
+ * @param params - Параметры запроса
36
+ * @returns Query объект
37
+ * @example
38
+ * const docQuery = docFetcher.queries.doc.createWithConfig(
39
+ * { fetchPolicy: 'network-only' },
40
+ * 'docId',
41
+ * )
42
+ * // Получает данные из query
43
+ * docQuery.sync()
44
+ */
45
+ createWithConfig: <TError = TDefaultError, TIsBackground extends boolean = false>(config: CreateQueryParams<Awaited<TResponse>, TError, TIsBackground>, ...params: TParams) => Query<TResponse, TError, TIsBackground>;
46
+ /**
47
+ * Инвалидирует текущий query в кэше
48
+ * @param keys - Дополнительные ключи для инвалидации. Если не указаны, то инвалидируется весь набор query
49
+ * @example
50
+ * const docFetcher = {
51
+ * doc: mobxQuery.createQuerySet((id: string) => ({
52
+ * execute: () => httpService.get(`/doc/${id}?page=${page}`),
53
+ * })),
54
+ * };
55
+ *
56
+ * // Инвалидирует все query doc
57
+ * docFetcher.doc.invalidate()
58
+ *
59
+ * // Инвалидирует query doc с конкретным переданным id. Доступные ключи инвалидации зависят от указанных additionalKeys, переданных при определении query в фабрике createDataFetcher
60
+ * docFetcher.doc.invalidate('docId')
61
+ */
62
+ invalidate: (...params: DeepPartial<TParams>) => void;
63
+ private configureQuery;
64
+ }