@astral/mobx-query 1.12.2 → 1.13.1

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.
@@ -15,7 +15,7 @@ export declare class DataStorage<TData> {
15
15
  /**
16
16
  * Метод для установки данных
17
17
  */
18
- setData: (value: TData) => void;
18
+ setData: (value: TData | ((data?: TData) => TData)) => void;
19
19
  cleanData: () => void;
20
20
  /**
21
21
  * Геттер данных
@@ -13,7 +13,10 @@ export class DataStorage {
13
13
  * Метод для установки данных
14
14
  */
15
15
  this.setData = (value) => {
16
- this.internalData = value;
16
+ this.internalData =
17
+ typeof value === 'function'
18
+ ? value(this.internalData)
19
+ : value;
17
20
  };
18
21
  this.cleanData = () => {
19
22
  this.internalData = undefined;
@@ -8,6 +8,10 @@ export type InfiniteParams = {
8
8
  offset: number;
9
9
  count: number;
10
10
  };
11
+ export type InfiniteDataStorage<TResult> = DataStorage<{
12
+ data: TResult[];
13
+ offset: number;
14
+ }>;
11
15
  /**
12
16
  * Исполнитель запроса, ожидается,
13
17
  * что будет использоваться что-то возвращающее массив данных
@@ -40,7 +44,7 @@ export type InfiniteQueryParams<TResult, TError, TIsBackground extends boolean =
40
44
  /**
41
45
  * Инстанс хранилища данных
42
46
  */
43
- dataStorage: DataStorage<TResult[]>;
47
+ dataStorage: InfiniteDataStorage<TResult>;
44
48
  /**
45
49
  * Инстанс хранилища фоновых статусов
46
50
  */
@@ -56,10 +60,6 @@ export type InfiniteQueryParams<TResult, TError, TIsBackground extends boolean =
56
60
  */
57
61
  export declare class InfiniteQuery<TResult, TError = void, TIsBackground extends boolean = false> extends QueryContainer<TError, AuxiliaryQuery<Array<TResult>, TError>, TIsBackground> implements QueryBaseActions<Array<TResult>, TError> {
58
62
  private readonly executor;
59
- /**
60
- * Счетчик отступа для инфинити запроса
61
- */
62
- private offset;
63
63
  /**
64
64
  * Количество запрашиваемых элементов
65
65
  */
@@ -90,6 +90,10 @@ export declare class InfiniteQuery<TResult, TError = void, TIsBackground extends
90
90
  private readonly submitValidity?;
91
91
  constructor(executor: InfiniteExecutor<TResult>, { incrementCount, onError, enabledAutoFetch, fetchPolicy, dataStorage, statusStorage, backgroundStatusStorage, submitValidity, }: InfiniteQueryParams<TResult, TError, TIsBackground>);
92
92
  private get isNetworkOnly();
93
+ /**
94
+ * Счетчик отступа для инфинити запроса
95
+ */
96
+ private get offset();
93
97
  /**
94
98
  * Обработчик успешного запроса, проверяет что мы достигли предела
95
99
  */
@@ -10,10 +10,6 @@ export class InfiniteQuery extends QueryContainer {
10
10
  constructor(executor, { incrementCount = DEFAULT_INFINITE_ITEMS_COUNT, onError, enabledAutoFetch, fetchPolicy, dataStorage, statusStorage, backgroundStatusStorage = null, submitValidity, }) {
11
11
  super(statusStorage, backgroundStatusStorage, new AuxiliaryQuery(statusStorage, backgroundStatusStorage));
12
12
  this.executor = executor;
13
- /**
14
- * Счетчик отступа для инфинити запроса
15
- */
16
- this.offset = 0;
17
13
  /**
18
14
  * Флаг того, что мы достигли предела запрашиваемых элементов
19
15
  */
@@ -25,10 +21,13 @@ export class InfiniteQuery extends QueryContainer {
25
21
  var _a;
26
22
  onSuccess === null || onSuccess === void 0 ? void 0 : onSuccess(result);
27
23
  if (isIncrement && this.storage.hasData) {
28
- this.storage.setData([...this.storage.data, ...result]);
24
+ this.storage.setData((current) => ({
25
+ offset: current === null || current === void 0 ? void 0 : current.offset,
26
+ data: [...current === null || current === void 0 ? void 0 : current.data, ...result],
27
+ }));
29
28
  }
30
29
  else {
31
- this.storage.setData(result);
30
+ this.storage.setData({ offset: 0, data: result });
32
31
  (_a = this.submitValidity) === null || _a === void 0 ? void 0 : _a.call(this);
33
32
  }
34
33
  // убеждаемся что результат запроса действительно массив,
@@ -46,9 +45,10 @@ export class InfiniteQuery extends QueryContainer {
46
45
  * Форс метод для установки данных
47
46
  */
48
47
  this.forceUpdate = (param) => {
48
+ var _a;
49
49
  this.auxiliary.submitSuccess();
50
50
  if (typeof param === 'function') {
51
- this.submitSuccess(param(this.storage.data));
51
+ this.submitSuccess(param((_a = this.storage.data) === null || _a === void 0 ? void 0 : _a.data));
52
52
  }
53
53
  else {
54
54
  this.submitSuccess(param);
@@ -67,7 +67,13 @@ export class InfiniteQuery extends QueryContainer {
67
67
  // если мы еще не достигли предела
68
68
  if (!this.isEndReached && this.storage.data) {
69
69
  // прибавляем к офсету число запрашиваемых элементов
70
- this.offset += this.incrementCount;
70
+ this.storage.setData((current) => {
71
+ var _a;
72
+ return ({
73
+ offset: ((_a = current === null || current === void 0 ? void 0 : current.offset) !== null && _a !== void 0 ? _a : 0) + this.incrementCount,
74
+ data: current === null || current === void 0 ? void 0 : current.data,
75
+ });
76
+ });
71
77
  // запускаем запрос с последними параметрами, и флагом необходимости инкремента
72
78
  this.auxiliary
73
79
  .getUnifiedPromise(this.infiniteExecutor, (resData) => {
@@ -80,21 +86,21 @@ export class InfiniteQuery extends QueryContainer {
80
86
  * Синхронный метод получения данных
81
87
  */
82
88
  this.sync = (params) => {
83
- var _a;
89
+ var _a, _b;
84
90
  const isInstanceAllow = !(this.isLoading || this.isSuccess);
85
91
  if (this.isNetworkOnly || this.auxiliary.isInvalid || isInstanceAllow) {
86
92
  this.proceedSync(params);
87
93
  return;
88
94
  }
89
95
  if (this.isSuccess) {
90
- (_a = params === null || params === void 0 ? void 0 : params.onSuccess) === null || _a === void 0 ? void 0 : _a.call(params, this.storage.data);
96
+ (_a = params === null || params === void 0 ? void 0 : params.onSuccess) === null || _a === void 0 ? void 0 : _a.call(params, (_b = this.storage.data) === null || _b === void 0 ? void 0 : _b.data);
91
97
  }
92
98
  };
93
99
  /**
94
100
  * Метод для переиспользования синхронной логики запроса
95
101
  */
96
102
  this.proceedSync = ({ onSuccess, onError, } = {}) => {
97
- this.offset = 0;
103
+ this.storage.setData((current) => ({ offset: 0, data: current === null || current === void 0 ? void 0 : current.data }));
98
104
  this.isEndReached = false;
99
105
  this.auxiliary
100
106
  .getUnifiedPromise(this.infiniteExecutor, (resData) => {
@@ -120,10 +126,11 @@ export class InfiniteQuery extends QueryContainer {
120
126
  * предполагается, что нужно будет самостоятельно обрабатывать ошибку
121
127
  */
122
128
  this.async = () => {
129
+ var _a;
123
130
  if (!this.isNetworkOnly && this.isSuccess && !this.auxiliary.isInvalid) {
124
- return Promise.resolve(this.storage.data);
131
+ return Promise.resolve((_a = this.storage.data) === null || _a === void 0 ? void 0 : _a.data);
125
132
  }
126
- this.offset = 0;
133
+ this.storage.setData((current) => ({ offset: 0, data: current === null || current === void 0 ? void 0 : current.data }));
127
134
  this.isEndReached = false;
128
135
  return this.auxiliary.getUnifiedPromise(this.infiniteExecutor, this.submitSuccess);
129
136
  };
@@ -147,6 +154,13 @@ export class InfiniteQuery extends QueryContainer {
147
154
  get isNetworkOnly() {
148
155
  return this.defaultFetchPolicy === 'network-only';
149
156
  }
157
+ /**
158
+ * Счетчик отступа для инфинити запроса
159
+ */
160
+ get offset() {
161
+ var _a, _b;
162
+ return (_b = (_a = this.storage.data) === null || _a === void 0 ? void 0 : _a.offset) !== null && _b !== void 0 ? _b : 0;
163
+ }
150
164
  /**
151
165
  * Метод для обогащения параметров текущими значениями для инфинити
152
166
  */
@@ -163,6 +177,7 @@ export class InfiniteQuery extends QueryContainer {
163
177
  * и начнется запрос, в результате которого, данные обновятся
164
178
  */
165
179
  get data() {
180
+ var _a;
166
181
  const shouldSync = this.enabledAutoFetch &&
167
182
  !this.isSuccess &&
168
183
  !this.isLoading &&
@@ -173,6 +188,6 @@ export class InfiniteQuery extends QueryContainer {
173
188
  when(() => true, this.proceedSync);
174
189
  }
175
190
  // возвращаем имеющиеся данные
176
- return this.storage.data;
191
+ return (_a = this.storage.data) === null || _a === void 0 ? void 0 : _a.data;
177
192
  }
178
193
  }
@@ -15,7 +15,7 @@ export declare class DataStorage<TData> {
15
15
  /**
16
16
  * Метод для установки данных
17
17
  */
18
- setData: (value: TData) => void;
18
+ setData: (value: TData | ((data?: TData) => TData)) => void;
19
19
  cleanData: () => void;
20
20
  /**
21
21
  * Геттер данных
@@ -16,7 +16,10 @@ class DataStorage {
16
16
  * Метод для установки данных
17
17
  */
18
18
  this.setData = (value) => {
19
- this.internalData = value;
19
+ this.internalData =
20
+ typeof value === 'function'
21
+ ? value(this.internalData)
22
+ : value;
20
23
  };
21
24
  this.cleanData = () => {
22
25
  this.internalData = undefined;
@@ -8,6 +8,10 @@ export type InfiniteParams = {
8
8
  offset: number;
9
9
  count: number;
10
10
  };
11
+ export type InfiniteDataStorage<TResult> = DataStorage<{
12
+ data: TResult[];
13
+ offset: number;
14
+ }>;
11
15
  /**
12
16
  * Исполнитель запроса, ожидается,
13
17
  * что будет использоваться что-то возвращающее массив данных
@@ -40,7 +44,7 @@ export type InfiniteQueryParams<TResult, TError, TIsBackground extends boolean =
40
44
  /**
41
45
  * Инстанс хранилища данных
42
46
  */
43
- dataStorage: DataStorage<TResult[]>;
47
+ dataStorage: InfiniteDataStorage<TResult>;
44
48
  /**
45
49
  * Инстанс хранилища фоновых статусов
46
50
  */
@@ -56,10 +60,6 @@ export type InfiniteQueryParams<TResult, TError, TIsBackground extends boolean =
56
60
  */
57
61
  export declare class InfiniteQuery<TResult, TError = void, TIsBackground extends boolean = false> extends QueryContainer<TError, AuxiliaryQuery<Array<TResult>, TError>, TIsBackground> implements QueryBaseActions<Array<TResult>, TError> {
58
62
  private readonly executor;
59
- /**
60
- * Счетчик отступа для инфинити запроса
61
- */
62
- private offset;
63
63
  /**
64
64
  * Количество запрашиваемых элементов
65
65
  */
@@ -90,6 +90,10 @@ export declare class InfiniteQuery<TResult, TError = void, TIsBackground extends
90
90
  private readonly submitValidity?;
91
91
  constructor(executor: InfiniteExecutor<TResult>, { incrementCount, onError, enabledAutoFetch, fetchPolicy, dataStorage, statusStorage, backgroundStatusStorage, submitValidity, }: InfiniteQueryParams<TResult, TError, TIsBackground>);
92
92
  private get isNetworkOnly();
93
+ /**
94
+ * Счетчик отступа для инфинити запроса
95
+ */
96
+ private get offset();
93
97
  /**
94
98
  * Обработчик успешного запроса, проверяет что мы достигли предела
95
99
  */
@@ -13,10 +13,6 @@ class InfiniteQuery extends QueryContainer_1.QueryContainer {
13
13
  constructor(executor, { incrementCount = exports.DEFAULT_INFINITE_ITEMS_COUNT, onError, enabledAutoFetch, fetchPolicy, dataStorage, statusStorage, backgroundStatusStorage = null, submitValidity, }) {
14
14
  super(statusStorage, backgroundStatusStorage, new AuxiliaryQuery_1.AuxiliaryQuery(statusStorage, backgroundStatusStorage));
15
15
  this.executor = executor;
16
- /**
17
- * Счетчик отступа для инфинити запроса
18
- */
19
- this.offset = 0;
20
16
  /**
21
17
  * Флаг того, что мы достигли предела запрашиваемых элементов
22
18
  */
@@ -28,10 +24,13 @@ class InfiniteQuery extends QueryContainer_1.QueryContainer {
28
24
  var _a;
29
25
  onSuccess === null || onSuccess === void 0 ? void 0 : onSuccess(result);
30
26
  if (isIncrement && this.storage.hasData) {
31
- this.storage.setData([...this.storage.data, ...result]);
27
+ this.storage.setData((current) => ({
28
+ offset: current === null || current === void 0 ? void 0 : current.offset,
29
+ data: [...current === null || current === void 0 ? void 0 : current.data, ...result],
30
+ }));
32
31
  }
33
32
  else {
34
- this.storage.setData(result);
33
+ this.storage.setData({ offset: 0, data: result });
35
34
  (_a = this.submitValidity) === null || _a === void 0 ? void 0 : _a.call(this);
36
35
  }
37
36
  // убеждаемся что результат запроса действительно массив,
@@ -49,9 +48,10 @@ class InfiniteQuery extends QueryContainer_1.QueryContainer {
49
48
  * Форс метод для установки данных
50
49
  */
51
50
  this.forceUpdate = (param) => {
51
+ var _a;
52
52
  this.auxiliary.submitSuccess();
53
53
  if (typeof param === 'function') {
54
- this.submitSuccess(param(this.storage.data));
54
+ this.submitSuccess(param((_a = this.storage.data) === null || _a === void 0 ? void 0 : _a.data));
55
55
  }
56
56
  else {
57
57
  this.submitSuccess(param);
@@ -70,7 +70,13 @@ class InfiniteQuery extends QueryContainer_1.QueryContainer {
70
70
  // если мы еще не достигли предела
71
71
  if (!this.isEndReached && this.storage.data) {
72
72
  // прибавляем к офсету число запрашиваемых элементов
73
- this.offset += this.incrementCount;
73
+ this.storage.setData((current) => {
74
+ var _a;
75
+ return ({
76
+ offset: ((_a = current === null || current === void 0 ? void 0 : current.offset) !== null && _a !== void 0 ? _a : 0) + this.incrementCount,
77
+ data: current === null || current === void 0 ? void 0 : current.data,
78
+ });
79
+ });
74
80
  // запускаем запрос с последними параметрами, и флагом необходимости инкремента
75
81
  this.auxiliary
76
82
  .getUnifiedPromise(this.infiniteExecutor, (resData) => {
@@ -83,21 +89,21 @@ class InfiniteQuery extends QueryContainer_1.QueryContainer {
83
89
  * Синхронный метод получения данных
84
90
  */
85
91
  this.sync = (params) => {
86
- var _a;
92
+ var _a, _b;
87
93
  const isInstanceAllow = !(this.isLoading || this.isSuccess);
88
94
  if (this.isNetworkOnly || this.auxiliary.isInvalid || isInstanceAllow) {
89
95
  this.proceedSync(params);
90
96
  return;
91
97
  }
92
98
  if (this.isSuccess) {
93
- (_a = params === null || params === void 0 ? void 0 : params.onSuccess) === null || _a === void 0 ? void 0 : _a.call(params, this.storage.data);
99
+ (_a = params === null || params === void 0 ? void 0 : params.onSuccess) === null || _a === void 0 ? void 0 : _a.call(params, (_b = this.storage.data) === null || _b === void 0 ? void 0 : _b.data);
94
100
  }
95
101
  };
96
102
  /**
97
103
  * Метод для переиспользования синхронной логики запроса
98
104
  */
99
105
  this.proceedSync = ({ onSuccess, onError, } = {}) => {
100
- this.offset = 0;
106
+ this.storage.setData((current) => ({ offset: 0, data: current === null || current === void 0 ? void 0 : current.data }));
101
107
  this.isEndReached = false;
102
108
  this.auxiliary
103
109
  .getUnifiedPromise(this.infiniteExecutor, (resData) => {
@@ -123,10 +129,11 @@ class InfiniteQuery extends QueryContainer_1.QueryContainer {
123
129
  * предполагается, что нужно будет самостоятельно обрабатывать ошибку
124
130
  */
125
131
  this.async = () => {
132
+ var _a;
126
133
  if (!this.isNetworkOnly && this.isSuccess && !this.auxiliary.isInvalid) {
127
- return Promise.resolve(this.storage.data);
134
+ return Promise.resolve((_a = this.storage.data) === null || _a === void 0 ? void 0 : _a.data);
128
135
  }
129
- this.offset = 0;
136
+ this.storage.setData((current) => ({ offset: 0, data: current === null || current === void 0 ? void 0 : current.data }));
130
137
  this.isEndReached = false;
131
138
  return this.auxiliary.getUnifiedPromise(this.infiniteExecutor, this.submitSuccess);
132
139
  };
@@ -150,6 +157,13 @@ class InfiniteQuery extends QueryContainer_1.QueryContainer {
150
157
  get isNetworkOnly() {
151
158
  return this.defaultFetchPolicy === 'network-only';
152
159
  }
160
+ /**
161
+ * Счетчик отступа для инфинити запроса
162
+ */
163
+ get offset() {
164
+ var _a, _b;
165
+ return (_b = (_a = this.storage.data) === null || _a === void 0 ? void 0 : _a.offset) !== null && _b !== void 0 ? _b : 0;
166
+ }
153
167
  /**
154
168
  * Метод для обогащения параметров текущими значениями для инфинити
155
169
  */
@@ -166,6 +180,7 @@ class InfiniteQuery extends QueryContainer_1.QueryContainer {
166
180
  * и начнется запрос, в результате которого, данные обновятся
167
181
  */
168
182
  get data() {
183
+ var _a;
169
184
  const shouldSync = this.enabledAutoFetch &&
170
185
  !this.isSuccess &&
171
186
  !this.isLoading &&
@@ -176,7 +191,7 @@ class InfiniteQuery extends QueryContainer_1.QueryContainer {
176
191
  (0, mobx_1.when)(() => true, this.proceedSync);
177
192
  }
178
193
  // возвращаем имеющиеся данные
179
- return this.storage.data;
194
+ return (_a = this.storage.data) === null || _a === void 0 ? void 0 : _a.data;
180
195
  }
181
196
  }
182
197
  exports.InfiniteQuery = InfiniteQuery;
package/package.json CHANGED
@@ -1,7 +1,5 @@
1
1
  {
2
2
  "name": "@astral/mobx-query",
3
- "version": "1.12.2",
4
- "browser": "./index.js",
5
3
  "main": "./node/index.js",
6
4
  "dependencies": {
7
5
  "@astral/utils": "^1.6.1",
@@ -9,19 +7,17 @@
9
7
  "mobx": "^6.9.0",
10
8
  "utility-types": "3.11.0"
11
9
  },
10
+ "version": "1.13.1",
12
11
  "author": "Astral.Soft",
13
12
  "license": "MIT",
14
13
  "repository": {
15
14
  "type": "git",
16
- "url": "git+https://github.com/kaluga-astral/mobx-query"
17
- },
18
- "bugs": {
19
- "url": "https://github.com/kaluga-astral/mobx-query/issues"
15
+ "url": "https://git.astralnalog.ru/frontend.shared/mobx-query"
20
16
  },
21
- "keywords": [],
22
- "sideEffects": false,
23
17
  "types": "./index.d.ts",
24
18
  "module": "./index.js",
19
+ "browser": "./index.js",
20
+ "sideEffects": false,
25
21
  "exports": {
26
22
  ".": {
27
23
  "module": "./index.js",