@astral/mobx-query 1.8.1 → 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 (58) 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/MobxQuery/MobxQuery.d.ts +44 -0
  31. package/node/MobxQuery/MobxQuery.js +48 -0
  32. package/node/Sets/InfiniteQuerySet/InfiniteQuerySet.d.ts +60 -0
  33. package/node/Sets/InfiniteQuerySet/InfiniteQuerySet.js +75 -0
  34. package/node/Sets/InfiniteQuerySet/index.d.ts +1 -0
  35. package/node/Sets/InfiniteQuerySet/index.js +17 -0
  36. package/node/Sets/MutationSet/MutationSet.d.ts +32 -0
  37. package/node/Sets/MutationSet/MutationSet.js +35 -0
  38. package/node/Sets/MutationSet/index.d.ts +1 -0
  39. package/node/Sets/MutationSet/index.js +17 -0
  40. package/node/Sets/QuerySet/QuerySet.d.ts +64 -0
  41. package/node/Sets/QuerySet/QuerySet.js +76 -0
  42. package/node/Sets/QuerySet/index.d.ts +1 -0
  43. package/node/Sets/QuerySet/index.js +17 -0
  44. package/node/Sets/index.d.ts +3 -0
  45. package/node/Sets/index.js +19 -0
  46. package/node/Sets/utils/generateQuerySetBaseKey/generateQuerySetBaseKey.d.ts +4 -0
  47. package/node/Sets/utils/generateQuerySetBaseKey/generateQuerySetBaseKey.js +12 -0
  48. package/node/Sets/utils/generateQuerySetBaseKey/index.d.ts +1 -0
  49. package/node/Sets/utils/generateQuerySetBaseKey/index.js +17 -0
  50. package/node/Sets/utils/generateQuerySetKeys/generateQuerySetKeys.d.ts +9 -0
  51. package/node/Sets/utils/generateQuerySetKeys/generateQuerySetKeys.js +27 -0
  52. package/node/Sets/utils/generateQuerySetKeys/index.d.ts +1 -0
  53. package/node/Sets/utils/generateQuerySetKeys/index.js +17 -0
  54. package/node/Sets/utils/index.d.ts +2 -0
  55. package/node/Sets/utils/index.js +18 -0
  56. package/node/index.d.ts +2 -1
  57. package/node/index.js +3 -1
  58. package/package.json +5 -2
@@ -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,71 @@
1
+ import { generateQuerySetBaseKey, generateQuerySetKeys } from '../utils';
2
+ /**
3
+ * Набор infinite queries под одним ключем с целью повышения читаемости кода и удобства инвалидации по общему ключу
4
+ */
5
+ export class InfiniteQuerySet {
6
+ constructor(_cache, _queryConfigurator, config) {
7
+ var _a;
8
+ this._cache = _cache;
9
+ this._queryConfigurator = _queryConfigurator;
10
+ /**
11
+ * Создает infinite query в кэше. Добавляет его в набор
12
+ * @returns InfiniteQuery объект
13
+ * @example
14
+ * const docListQuery = docFetcher.infiniteQueries.docList.create()
15
+ * // Получает данные
16
+ * docListQuery.sync()
17
+ */
18
+ this.create = (...params) => {
19
+ const { keys, execute } = this.configureQuery(...params);
20
+ return this._cache.createInfiniteQuery(keys, execute);
21
+ };
22
+ /**
23
+ * Создает infinite query в кэше с дополнительными параметрами конфигурации. Добавляет его в набор
24
+ * @param config - Параметры конфигурации infinite query. Например, fetchPolicy или incrementCount
25
+ * @param params - Параметры запроса
26
+ * @returns InfiniteQuery объект
27
+ * @example
28
+ * const docListQuery = docFetcher.infiniteQueries.docList.createWithConfig(
29
+ * { fetchPolicy: 'network-only', incrementCount: 10 },
30
+ * 'docId',
31
+ * )
32
+ * // Получает данные из query
33
+ * docListQuery.sync()
34
+ */
35
+ this.createWithConfig = (config, ...params) => {
36
+ const { keys, execute } = this.configureQuery(...params);
37
+ return this._cache.createInfiniteQuery(keys, execute, config);
38
+ };
39
+ /**
40
+ * Инвалидирует текущий набор infinite queries в кэше
41
+ * @param params - Параметры функции, переданной в createInfiniteQuerySet при создании набора. Если не указаны, то инвалидируется все query
42
+ * @example
43
+ * const docFetcher = {
44
+ * infiniteQueries: {
45
+ * docList: createInfiniteQuerySet('docList', (search: string) => ({
46
+ * execute: ({ count, offset }) => httpService.get(`/doc/${search}?count=${count}&offset=${offset}`),
47
+ * }),
48
+ * }
49
+ * };
50
+ *
51
+ * // Инвалидирует infinite query с конкретным переданным search
52
+ * docFetcher.infiniteQueries.docList.invalidate('документ1')
53
+ */
54
+ this.invalidate = (...params) => {
55
+ if (params.length === 0) {
56
+ this._cache.invalidate([this.baseKey]);
57
+ return;
58
+ }
59
+ const { keys } = this.configureQuery(...params);
60
+ this._cache.invalidate(keys, 'chain-match');
61
+ };
62
+ this.configureQuery = (...params) => {
63
+ const { keys, execute } = this._queryConfigurator(...params);
64
+ return {
65
+ keys: generateQuerySetKeys(this.baseKey, keys !== null && keys !== void 0 ? keys : params),
66
+ execute,
67
+ };
68
+ };
69
+ this.baseKey = (_a = config === null || config === void 0 ? void 0 : config.name) !== null && _a !== void 0 ? _a : generateQuerySetBaseKey(_queryConfigurator);
70
+ }
71
+ }
@@ -0,0 +1 @@
1
+ export * from './InfiniteQuerySet';
@@ -0,0 +1 @@
1
+ export * from './InfiniteQuerySet';
@@ -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,31 @@
1
+ /**
2
+ * Налор мутаций. Цель: единый интерфейс создания и использования наборов Query и Mutation
3
+ * @example
4
+ * const docFetcher = {
5
+ * mutations: {
6
+ * editDoc: mobxQuery.createMutationSet((params: DocsEndpointsDTO.EditDocInput) => {
7
+ * return docsEndpoint.editDoc(params);
8
+ * }),
9
+ * },
10
+ * queries: {
11
+ * doc: mobxQuery.createQuerySet((id: string) => ({
12
+ * execute: () => docsEndpoint.getDoc(id).then(({ data }) => data),
13
+ * })),
14
+ * },
15
+ * }
16
+ */
17
+ export class MutationSet {
18
+ constructor(_cache, _executor) {
19
+ this._cache = _cache;
20
+ this._executor = _executor;
21
+ /**
22
+ * Создает мутацию
23
+ * @returns Mutation объект
24
+ * @example
25
+ * const editDocMutation = docFetcher.mutations.editDoc.create();
26
+ * // Выполняет мутацию
27
+ * editDocMutation.sync({ params: { id: 'docId', content: 'Новое содержимое' } });
28
+ */
29
+ this.create = () => this._cache.createMutation(this._executor);
30
+ }
31
+ }
@@ -0,0 +1 @@
1
+ export * from './MutationSet';
@@ -0,0 +1 @@
1
+ export * from './MutationSet';
@@ -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
+ }
@@ -0,0 +1,72 @@
1
+ import { generateQuerySetBaseKey, generateQuerySetKeys } from '../utils';
2
+ /**
3
+ * Набор queries под одним ключем с целью повышения читаемости кода и удобства инвалидации по общему ключу
4
+ */
5
+ export class QuerySet {
6
+ constructor(_cache, _queryConfigurator, config) {
7
+ var _a;
8
+ this._cache = _cache;
9
+ this._queryConfigurator = _queryConfigurator;
10
+ /**
11
+ * Создает query в кэше. Добавляет его в набор
12
+ * @returns Query объект
13
+ * @example
14
+ * const docQuery = docFetcher.queries.doc.create('docId')
15
+ * // Получает данные
16
+ * docQuery.sync()
17
+ */
18
+ this.create = (...params) => {
19
+ const { keys, execute } = this.configureQuery(...params);
20
+ return this._cache.createQuery(keys, execute);
21
+ };
22
+ /**
23
+ * Создает query в кэше с дополнительными параметрами конфигурации. Добавляет его в набор
24
+ * @param config - Параметры конфигурации query. Например, fetchPolicy
25
+ * @param params - Параметры запроса
26
+ * @returns Query объект
27
+ * @example
28
+ * const docQuery = docFetcher.queries.doc.createWithConfig(
29
+ * { fetchPolicy: 'network-only' },
30
+ * 'docId',
31
+ * )
32
+ * // Получает данные из query
33
+ * docQuery.sync()
34
+ */
35
+ this.createWithConfig = (config, ...params) => {
36
+ const { keys, execute } = this.configureQuery(...params);
37
+ return this._cache.createQuery(keys, execute, config);
38
+ };
39
+ /**
40
+ * Инвалидирует текущий query в кэше
41
+ * @param keys - Дополнительные ключи для инвалидации. Если не указаны, то инвалидируется весь набор query
42
+ * @example
43
+ * const docFetcher = {
44
+ * doc: mobxQuery.createQuerySet((id: string) => ({
45
+ * execute: () => httpService.get(`/doc/${id}?page=${page}`),
46
+ * })),
47
+ * };
48
+ *
49
+ * // Инвалидирует все query doc
50
+ * docFetcher.doc.invalidate()
51
+ *
52
+ * // Инвалидирует query doc с конкретным переданным id. Доступные ключи инвалидации зависят от указанных additionalKeys, переданных при определении query в фабрике createDataFetcher
53
+ * docFetcher.doc.invalidate('docId')
54
+ */
55
+ this.invalidate = (...params) => {
56
+ if (params.length === 0) {
57
+ this._cache.invalidate([this.baseKey]);
58
+ return;
59
+ }
60
+ const { keys } = this.configureQuery(...params);
61
+ this._cache.invalidate(keys, 'chain-match');
62
+ };
63
+ this.configureQuery = (...params) => {
64
+ const { keys, execute } = this._queryConfigurator(...params);
65
+ return {
66
+ keys: generateQuerySetKeys(this.baseKey, keys !== null && keys !== void 0 ? keys : params),
67
+ execute,
68
+ };
69
+ };
70
+ this.baseKey = (_a = config === null || config === void 0 ? void 0 : config.name) !== null && _a !== void 0 ? _a : generateQuerySetBaseKey(_queryConfigurator);
71
+ }
72
+ }
@@ -0,0 +1 @@
1
+ export * from './QuerySet';
@@ -0,0 +1 @@
1
+ export * from './QuerySet';
@@ -0,0 +1,3 @@
1
+ export * from './MutationSet';
2
+ export * from './QuerySet';
3
+ export * from './InfiniteQuerySet';
package/Sets/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export * from './MutationSet';
2
+ export * from './QuerySet';
3
+ export * from './InfiniteQuerySet';
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Создает базовый ключ на основе хэша от configurator
3
+ */
4
+ export declare const generateQuerySetBaseKey: (configurator: Function) => string;
@@ -0,0 +1,5 @@
1
+ import hash from '@emotion/hash';
2
+ /**
3
+ * Создает базовый ключ на основе хэша от configurator
4
+ */
5
+ export const generateQuerySetBaseKey = (configurator) => hash(configurator.toString());
@@ -0,0 +1 @@
1
+ export * from './generateQuerySetBaseKey';
@@ -0,0 +1 @@
1
+ export * from './generateQuerySetBaseKey';
@@ -0,0 +1,9 @@
1
+ import { type CacheKey } from '../../../types';
2
+ /**
3
+ * Создает ключи на основе каждого параметра
4
+ * @param additionalKeys - Создает для каждого параметра отдельный ключ, чтобы по нему можно было инвалидировать query
5
+ * @example
6
+ * // Создаст ключи ['22f4', ['22f4', 'organizationID', '1'], ['22f4', 'employeeID', '2']]
7
+ * generateQuerySetKeys('22f4', params)
8
+ */
9
+ export declare const generateQuerySetKeys: (baseKey: string, params: CacheKey[]) => CacheKey[];
@@ -0,0 +1,20 @@
1
+ import isPlainObj from 'is-plain-obj';
2
+ /**
3
+ * Создает ключи на основе каждого параметра
4
+ * @param additionalKeys - Создает для каждого параметра отдельный ключ, чтобы по нему можно было инвалидировать query
5
+ * @example
6
+ * // Создаст ключи ['22f4', ['22f4', 'organizationID', '1'], ['22f4', 'employeeID', '2']]
7
+ * generateQuerySetKeys('22f4', params)
8
+ */
9
+ export const generateQuerySetKeys = (baseKey, params) => {
10
+ const resultKeys = [];
11
+ params.forEach((param) => {
12
+ if (isPlainObj(param)) {
13
+ resultKeys.push(...Object.entries(param).map(([key, value]) => [baseKey, key, value]));
14
+ }
15
+ else {
16
+ resultKeys.push(param);
17
+ }
18
+ });
19
+ return [baseKey, ...resultKeys];
20
+ };
@@ -0,0 +1 @@
1
+ export * from './generateQuerySetKeys';
@@ -0,0 +1 @@
1
+ export * from './generateQuerySetKeys';
@@ -0,0 +1,2 @@
1
+ export * from './generateQuerySetKeys';
2
+ export * from './generateQuerySetBaseKey';
@@ -0,0 +1,2 @@
1
+ export * from './generateQuerySetKeys';
2
+ export * from './generateQuerySetBaseKey';
package/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export { Mutation } from './Mutation';
2
2
  export { Query } from './Query';
3
- export { type InfiniteParams } from './InfiniteQuery';
3
+ export { type InfiniteParams, InfiniteQuery } from './InfiniteQuery';
4
4
  export { MobxQuery, type CreateQueryParams, type CreateInfiniteQueryParams, type CreateMutationParams, } from './MobxQuery';
5
+ export { type QuerySet, type InfiniteQuerySet, type MutationSet } from './Sets';
5
6
  export { type CacheKey, type FetchPolicy } from './types';
package/index.js CHANGED
@@ -1,3 +1,4 @@
1
1
  export { Mutation } from './Mutation';
2
2
  export { Query } from './Query';
3
+ export { InfiniteQuery } from './InfiniteQuery';
3
4
  export { MobxQuery, } from './MobxQuery';
@@ -2,6 +2,7 @@ import { Query, type QueryExecutor, type QueryParams } from '../Query';
2
2
  import { type InfiniteExecutor, InfiniteQuery, type InfiniteQueryParams } from '../InfiniteQuery';
3
3
  import { Mutation, type MutationExecutor, type MutationParams } from '../Mutation';
4
4
  import type { CacheKey, FetchPolicy } from '../types';
5
+ import { InfiniteQuerySet, type InfiniteQuerySetConfig, type InfiniteQuerySetConfigurator, MutationSet, QuerySet, type QuerySetConfig, type QuerySetConfigurator } from '../Sets';
5
6
  /**
6
7
  * Стандартный обработчик ошибки запроса,
7
8
  * будет вызван, если при вызове sync не был передан отдельный onError параметр
@@ -128,5 +129,48 @@ export declare class MobxQuery<TDefaultError = void> {
128
129
  * Метод создания мутации, не кешируется
129
130
  */
130
131
  createMutation: <TResult, TError = TDefaultError, TExecutorParams = void>(executor: MutationExecutor<TResult, TExecutorParams>, params?: CreateMutationParams<TResult, TError>) => Mutation<TResult, TError, TExecutorParams>;
132
+ /**
133
+ * Создает набор queries под одним ключем
134
+ * @param configurator - Функция конфигурации набора запросов. Она должна возвращать объект с полями:
135
+ * - keys (необязательно): массив ключей для кеширования;
136
+ * - execute: функция, которая возвращает промис с результатом выполнения запроса.
137
+ * @example
138
+ * const docQuerySet = mobxQuery.createQuerySet((id: string, count?: number) => ({
139
+ * execute: () => docEndpoint.getDoc(id),
140
+ * }));
141
+ *
142
+ * const docQuery = docQuerySet.create();
143
+ *
144
+ * docQuery.data // { data: [id, count] }
145
+ */
146
+ createQuerySet: <TParams extends any[], TResponse>(configurator: QuerySetConfigurator<TParams, TResponse>, config?: QuerySetConfig) => QuerySet<TParams, TResponse, TDefaultError>;
147
+ /**
148
+ * Создает набор infinite queries под одним ключем
149
+ * @param configurator - Функция конфигурации набора запросов. Она должна возвращать объект с полями:
150
+ * - keys (необязательно): массив ключей для кеширования;
151
+ * - execute: функция, которая возвращает промис с результатом выполнения запроса.
152
+ * @example
153
+ * const docListInfiniteQuerySet = mobxQuery.createInfiniteQuerySet((id: string, count?: number) => ({
154
+ * execute: ({ offset, count }) => docEndpoint.getDocList(id, offset, count),
155
+ * }));
156
+ *
157
+ * const docListInfiniteQuery = docListInfiniteQuerySet.create();
158
+ *
159
+ * docListInfiniteQuery.data
160
+ */
161
+ createInfiniteQuerySet: <TParams extends any[], TResponse>(configurator: InfiniteQuerySetConfigurator<TParams, TResponse>, config?: InfiniteQuerySetConfig) => InfiniteQuerySet<TParams, TResponse, TDefaultError>;
162
+ /**
163
+ * Создает набор мутаций для единого интерфейса с query sets
164
+ * @param executor - Функция-исполнитель мутации. Она должна возвращать промис с результатом выполнения мутации.
165
+ * @example
166
+ * const editDocMutationSet = mobxQuery.createMutationSet((params: DocsEndpointsDTO.EditDocInput) => {
167
+ * return docsEndpoint.editDoc(params);
168
+ * });
169
+ *
170
+ * const editDocMutation = editDocMutationSet.create();
171
+ *
172
+ * editDocMutation.sync({ params: { id: 'docId', content: 'Новое содержимое' } });
173
+ */
174
+ createMutationSet: <TResponse, TExecutorParams = void>(executor: MutationExecutor<TResponse, TExecutorParams>) => MutationSet<TResponse, TExecutorParams, TDefaultError>;
131
175
  }
132
176
  export {};
@@ -7,6 +7,7 @@ const Mutation_1 = require("../Mutation");
7
7
  const DataStorage_1 = require("../DataStorage");
8
8
  const StatusStorage_1 = require("../StatusStorage");
9
9
  const AdaptableMap_1 = require("../AdaptableMap");
10
+ const Sets_1 = require("../Sets");
10
11
  /**
11
12
  * Сервис, позволяющий кэшировать данные.
12
13
  */
@@ -169,6 +170,53 @@ class MobxQuery {
169
170
  * Метод создания мутации, не кешируется
170
171
  */
171
172
  this.createMutation = (executor, params) => new Mutation_1.Mutation(executor, Object.assign(Object.assign({}, params), { onError: (params === null || params === void 0 ? void 0 : params.onError) || this.defaultErrorHandler }));
173
+ /**
174
+ * Создает набор queries под одним ключем
175
+ * @param configurator - Функция конфигурации набора запросов. Она должна возвращать объект с полями:
176
+ * - keys (необязательно): массив ключей для кеширования;
177
+ * - execute: функция, которая возвращает промис с результатом выполнения запроса.
178
+ * @example
179
+ * const docQuerySet = mobxQuery.createQuerySet((id: string, count?: number) => ({
180
+ * execute: () => docEndpoint.getDoc(id),
181
+ * }));
182
+ *
183
+ * const docQuery = docQuerySet.create();
184
+ *
185
+ * docQuery.data // { data: [id, count] }
186
+ */
187
+ // any нужен для вывода типов
188
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
189
+ this.createQuerySet = (configurator, config) => new Sets_1.QuerySet(this, configurator, config);
190
+ /**
191
+ * Создает набор infinite queries под одним ключем
192
+ * @param configurator - Функция конфигурации набора запросов. Она должна возвращать объект с полями:
193
+ * - keys (необязательно): массив ключей для кеширования;
194
+ * - execute: функция, которая возвращает промис с результатом выполнения запроса.
195
+ * @example
196
+ * const docListInfiniteQuerySet = mobxQuery.createInfiniteQuerySet((id: string, count?: number) => ({
197
+ * execute: ({ offset, count }) => docEndpoint.getDocList(id, offset, count),
198
+ * }));
199
+ *
200
+ * const docListInfiniteQuery = docListInfiniteQuerySet.create();
201
+ *
202
+ * docListInfiniteQuery.data
203
+ */
204
+ // any нужен для вывода типов
205
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
206
+ this.createInfiniteQuerySet = (configurator, config) => new Sets_1.InfiniteQuerySet(this, configurator, config);
207
+ /**
208
+ * Создает набор мутаций для единого интерфейса с query sets
209
+ * @param executor - Функция-исполнитель мутации. Она должна возвращать промис с результатом выполнения мутации.
210
+ * @example
211
+ * const editDocMutationSet = mobxQuery.createMutationSet((params: DocsEndpointsDTO.EditDocInput) => {
212
+ * return docsEndpoint.editDoc(params);
213
+ * });
214
+ *
215
+ * const editDocMutation = editDocMutationSet.create();
216
+ *
217
+ * editDocMutation.sync({ params: { id: 'docId', content: 'Новое содержимое' } });
218
+ */
219
+ this.createMutationSet = (executor) => new Sets_1.MutationSet(this, executor);
172
220
  this.defaultErrorHandler = onError;
173
221
  this.defaultFetchPolicy = fetchPolicy;
174
222
  this.defaultEnabledAutoFetch = enabledAutoFetch;
@@ -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
+ }