@legendapp/state 2.2.0-next.75 → 2.2.0-next.76
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/helpers/time.d.ts +2 -2
- package/index.js +7 -5
- package/index.js.map +1 -1
- package/index.mjs +7 -5
- package/index.mjs.map +1 -1
- package/package.json +11 -1
- package/persist.js +82 -87
- package/persist.js.map +1 -1
- package/persist.mjs +82 -87
- package/persist.mjs.map +1 -1
- package/src/batching.ts +2 -0
- package/src/computed.ts +4 -2
- package/src/globals.ts +1 -1
- package/src/helpers.ts +1 -1
- package/src/history/undoRedo.ts +111 -0
- package/src/observableInterfaces.ts +6 -5
- package/src/observe.ts +1 -1
- package/src/sync/activateSyncedNode.ts +2 -20
- package/src/sync/syncObservable.ts +88 -73
- package/src/sync-plugins/crud.ts +109 -98
- package/src/sync-plugins/fetch.ts +56 -26
- package/src/sync-plugins/keel.ts +447 -0
- package/src/sync-plugins/supabase.ts +225 -0
- package/src/syncTypes.ts +10 -4
- package/sync-plugins/crud.d.ts +27 -26
- package/sync-plugins/crud.js +50 -42
- package/sync-plugins/crud.js.map +1 -1
- package/sync-plugins/crud.mjs +50 -42
- package/sync-plugins/crud.mjs.map +1 -1
- package/sync-plugins/fetch.d.ts +8 -7
- package/sync-plugins/fetch.js +33 -11
- package/sync-plugins/fetch.js.map +1 -1
- package/sync-plugins/fetch.mjs +34 -12
- package/sync-plugins/fetch.mjs.map +1 -1
- package/sync-plugins/keel.d.ts +91 -0
- package/sync-plugins/keel.js +278 -0
- package/sync-plugins/keel.js.map +1 -0
- package/sync-plugins/keel.mjs +274 -0
- package/sync-plugins/keel.mjs.map +1 -0
- package/sync-plugins/supabase.d.ts +32 -0
- package/sync-plugins/supabase.js +134 -0
- package/sync-plugins/supabase.js.map +1 -0
- package/sync-plugins/supabase.mjs +131 -0
- package/sync-plugins/supabase.mjs.map +1 -0
- package/sync.js +82 -87
- package/sync.js.map +1 -1
- package/sync.mjs +83 -88
- package/sync.mjs.map +1 -1
|
@@ -1,42 +1,72 @@
|
|
|
1
|
-
import { Synced, SyncedOptions, SyncedSetParams,
|
|
1
|
+
import { Selector, SyncTransform, Synced, SyncedOptions, SyncedSetParams, computeSelector } from '@legendapp/state';
|
|
2
2
|
import { synced } from '@legendapp/state/sync';
|
|
3
3
|
|
|
4
|
-
export interface SyncedFetchProps extends Omit<SyncedOptions, 'get' | 'set'> {
|
|
5
|
-
get: string
|
|
6
|
-
set?: string
|
|
4
|
+
export interface SyncedFetchProps<TRemote, TLocal> extends Omit<SyncedOptions, 'get' | 'set' | 'transform'> {
|
|
5
|
+
get: Selector<string>;
|
|
6
|
+
set?: Selector<string>;
|
|
7
7
|
getInit?: RequestInit;
|
|
8
8
|
setInit?: RequestInit;
|
|
9
|
+
transform?: SyncTransform<TLocal, TRemote>;
|
|
9
10
|
valueType?: 'arrayBuffer' | 'blob' | 'formData' | 'json' | 'text';
|
|
10
|
-
|
|
11
|
-
|
|
11
|
+
onSavedValueType?: 'arrayBuffer' | 'blob' | 'formData' | 'json' | 'text';
|
|
12
|
+
onSaved?(saved: TLocal, input: TRemote): Partial<TLocal> | void;
|
|
12
13
|
}
|
|
13
14
|
|
|
14
|
-
export function syncedFetch<
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
15
|
+
export function syncedFetch<TRemote, TLocal = TRemote>(props: SyncedFetchProps<TRemote, TLocal>): Synced<TLocal> {
|
|
16
|
+
const {
|
|
17
|
+
get: getParam,
|
|
18
|
+
set: setParam,
|
|
19
|
+
getInit,
|
|
20
|
+
setInit,
|
|
21
|
+
valueType,
|
|
22
|
+
onSaved,
|
|
23
|
+
onSavedValueType,
|
|
24
|
+
transform,
|
|
25
|
+
...rest
|
|
26
|
+
} = props;
|
|
27
|
+
const get = async () => {
|
|
28
|
+
const url = computeSelector(getParam);
|
|
29
|
+
const response = await fetch(url, getInit);
|
|
30
|
+
|
|
31
|
+
if (!response.ok) {
|
|
32
|
+
throw new Error(response.statusText);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
let value = await response[valueType || 'json']();
|
|
36
|
+
|
|
37
|
+
if (transform?.load) {
|
|
38
|
+
value = transform?.load(value);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
return value;
|
|
25
42
|
};
|
|
26
43
|
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
44
|
+
let set: ((params: SyncedSetParams<TRemote>) => void | Promise<any>) | undefined = undefined;
|
|
45
|
+
if (setParam) {
|
|
46
|
+
set = async ({ value, update }: SyncedSetParams<any>) => {
|
|
47
|
+
const url = computeSelector(setParam);
|
|
48
|
+
|
|
30
49
|
const response = await fetch(
|
|
31
|
-
|
|
32
|
-
setInit,
|
|
50
|
+
url,
|
|
51
|
+
Object.assign({ method: 'POST' }, setInit, { body: JSON.stringify(value) }),
|
|
33
52
|
);
|
|
34
|
-
if (
|
|
35
|
-
|
|
36
|
-
|
|
53
|
+
if (!response.ok) {
|
|
54
|
+
throw new Error(response.statusText);
|
|
55
|
+
}
|
|
56
|
+
if (onSaved) {
|
|
57
|
+
const responseValue = await response[onSavedValueType || valueType || 'json']();
|
|
58
|
+
const transformed = transform?.load ? await transform.load(responseValue) : responseValue;
|
|
59
|
+
const valueSave = onSaved(transformed, value);
|
|
60
|
+
update({
|
|
61
|
+
value: valueSave,
|
|
62
|
+
});
|
|
37
63
|
}
|
|
38
64
|
};
|
|
39
65
|
}
|
|
40
66
|
|
|
41
|
-
return synced(
|
|
67
|
+
return synced({
|
|
68
|
+
...rest,
|
|
69
|
+
get,
|
|
70
|
+
set,
|
|
71
|
+
});
|
|
42
72
|
}
|
|
@@ -0,0 +1,447 @@
|
|
|
1
|
+
import {
|
|
2
|
+
SyncedSetParams,
|
|
3
|
+
computeSelector,
|
|
4
|
+
internal,
|
|
5
|
+
observable,
|
|
6
|
+
when,
|
|
7
|
+
type SyncedGetParams,
|
|
8
|
+
type SyncedSubscribeParams,
|
|
9
|
+
} from '@legendapp/state';
|
|
10
|
+
import {
|
|
11
|
+
CrudAsOption,
|
|
12
|
+
CrudResult,
|
|
13
|
+
SyncedCrudPropsBase,
|
|
14
|
+
SyncedCrudPropsMany,
|
|
15
|
+
SyncedCrudPropsSingle,
|
|
16
|
+
SyncedCrudReturnType,
|
|
17
|
+
syncedCrud,
|
|
18
|
+
} from '@legendapp/state/sync-plugins/crud';
|
|
19
|
+
const { clone } = internal;
|
|
20
|
+
|
|
21
|
+
// Keel types
|
|
22
|
+
export interface KeelObjectBase {
|
|
23
|
+
id: string;
|
|
24
|
+
createdAt: Date;
|
|
25
|
+
updatedAt: Date;
|
|
26
|
+
}
|
|
27
|
+
export type KeelKey = 'createdAt' | 'updatedAt';
|
|
28
|
+
export const KeelKeys: KeelKey[] = ['createdAt', 'updatedAt'];
|
|
29
|
+
export type OmitKeelBuiltins<T, T2 extends string = ''> = Omit<T, KeelKey | T2>;
|
|
30
|
+
type APIError = { type: string; message: string; requestId?: string };
|
|
31
|
+
|
|
32
|
+
type APIResult<T> = Result<T, APIError>;
|
|
33
|
+
|
|
34
|
+
type Data<T> = {
|
|
35
|
+
data: T;
|
|
36
|
+
error?: never;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
type Err<U> = {
|
|
40
|
+
data?: never;
|
|
41
|
+
error: U;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
type Result<T, U> = NonNullable<Data<T> | Err<U>>;
|
|
45
|
+
|
|
46
|
+
// Keel plugin types
|
|
47
|
+
|
|
48
|
+
interface GetGetParams {
|
|
49
|
+
refresh: () => void;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
interface ListGetParams {
|
|
53
|
+
where: { updatedAt?: { after: Date } };
|
|
54
|
+
refresh?: () => void;
|
|
55
|
+
after?: string;
|
|
56
|
+
first?: number;
|
|
57
|
+
maxResults?: number;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface KeelRealtimePlugin {
|
|
61
|
+
subscribe: (realtimeKey: string, refresh: () => void) => void;
|
|
62
|
+
setLatestChange: (realtimeKey: string, time: Date) => void;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
interface SyncedKeelConfiguration {
|
|
66
|
+
client: {
|
|
67
|
+
auth: { refresh: () => Promise<boolean>; isAuthenticated: () => Promise<boolean> };
|
|
68
|
+
api: { queries: Record<string, (i: any) => Promise<any>> };
|
|
69
|
+
};
|
|
70
|
+
realtimePlugin?: KeelRealtimePlugin;
|
|
71
|
+
as?: CrudAsOption;
|
|
72
|
+
enabled?: boolean;
|
|
73
|
+
onError?: (params: APIResult<any>['error']) => void;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
interface PageInfo {
|
|
77
|
+
count: number;
|
|
78
|
+
endCursor: string;
|
|
79
|
+
hasNextPage: boolean;
|
|
80
|
+
startCursor: string;
|
|
81
|
+
totalCount: number;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
interface SyncedKeelPropsMany<TRemote, TLocal, AOption extends CrudAsOption>
|
|
85
|
+
extends Omit<SyncedCrudPropsMany<TRemote, TLocal, AOption>, 'list'> {
|
|
86
|
+
list?: (params: ListGetParams) => Promise<CrudResult<APIResult<{ results: TRemote[]; pageInfo: any }>>>;
|
|
87
|
+
maxResults?: number;
|
|
88
|
+
get?: never;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
interface SyncedKeelPropsSingle<TRemote, TLocal> extends Omit<SyncedCrudPropsSingle<TRemote, TLocal>, 'get'> {
|
|
92
|
+
get?: (params: GetGetParams) => Promise<APIResult<TRemote>>;
|
|
93
|
+
|
|
94
|
+
maxResults?: never;
|
|
95
|
+
list?: never;
|
|
96
|
+
as?: never;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
interface SyncedKeelPropsBase<TRemote extends { id: string }, TLocal = TRemote>
|
|
100
|
+
extends Omit<SyncedCrudPropsBase<TRemote, TLocal>, 'create' | 'update' | 'delete'> {
|
|
101
|
+
create?: (i: NoInfer<Partial<TRemote>>) => Promise<APIResult<NoInfer<TRemote>>>;
|
|
102
|
+
update?: (params: { where: any; values?: Partial<TRemote> }) => Promise<APIResult<TRemote>>;
|
|
103
|
+
delete?: (params: { id: string }) => Promise<APIResult<string>>;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
let _client: SyncedKeelConfiguration['client'];
|
|
107
|
+
let _asOption: CrudAsOption;
|
|
108
|
+
let _realtimePlugin: KeelRealtimePlugin;
|
|
109
|
+
let _onError: (error: APIResult<any>['error']) => void;
|
|
110
|
+
const modifiedClients = new WeakSet<Record<string, any>>();
|
|
111
|
+
const isEnabled$ = observable(true);
|
|
112
|
+
|
|
113
|
+
async function ensureAuthToken() {
|
|
114
|
+
await when(isEnabled$.get());
|
|
115
|
+
let isAuthed = await _client.auth.isAuthenticated();
|
|
116
|
+
if (!isAuthed) {
|
|
117
|
+
isAuthed = await _client.auth.refresh();
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
return isAuthed;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async function handleApiError(error: APIError, retry?: () => any) {
|
|
124
|
+
if (error.type === 'unauthorized' || error.type === 'forbidden') {
|
|
125
|
+
console.warn('Keel token expired, refreshing...');
|
|
126
|
+
await ensureAuthToken();
|
|
127
|
+
// Retry
|
|
128
|
+
retry?.();
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function convertObjectToCreate<TRemote, TLocal>(item: TRemote) {
|
|
133
|
+
const cloned = clone(item);
|
|
134
|
+
Object.keys(cloned).forEach((key) => {
|
|
135
|
+
if (key.endsWith('Id')) {
|
|
136
|
+
if (cloned[key]) {
|
|
137
|
+
cloned[key.slice(0, -2)] = { id: cloned[key] };
|
|
138
|
+
}
|
|
139
|
+
delete cloned[key];
|
|
140
|
+
}
|
|
141
|
+
});
|
|
142
|
+
delete cloned.createdAt;
|
|
143
|
+
delete cloned.updatedAt;
|
|
144
|
+
return cloned as unknown as TLocal;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function configureSyncedKeel({
|
|
148
|
+
realtimePlugin,
|
|
149
|
+
as: asOption,
|
|
150
|
+
client,
|
|
151
|
+
enabled,
|
|
152
|
+
onError,
|
|
153
|
+
}: SyncedKeelConfiguration) {
|
|
154
|
+
if (asOption) {
|
|
155
|
+
_asOption = asOption;
|
|
156
|
+
}
|
|
157
|
+
if (client) {
|
|
158
|
+
_client = client;
|
|
159
|
+
}
|
|
160
|
+
if (enabled !== undefined) {
|
|
161
|
+
isEnabled$.set(enabled);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
if (realtimePlugin) {
|
|
165
|
+
_realtimePlugin = realtimePlugin;
|
|
166
|
+
if (client && !modifiedClients.has(client)) {
|
|
167
|
+
modifiedClients.add(client);
|
|
168
|
+
const queries = client.api.queries;
|
|
169
|
+
Object.keys(queries).forEach((key) => {
|
|
170
|
+
const oldFn = queries[key];
|
|
171
|
+
queries[key] = (i) => {
|
|
172
|
+
const subscribe =
|
|
173
|
+
key.startsWith('list') &&
|
|
174
|
+
i.where &&
|
|
175
|
+
(({ refresh }: SyncedSubscribeParams) => {
|
|
176
|
+
const realtimeChild = Object.values(i.where)
|
|
177
|
+
.filter((value) => value && typeof value !== 'object')
|
|
178
|
+
.join('/');
|
|
179
|
+
|
|
180
|
+
if (realtimeChild) {
|
|
181
|
+
const realtimeKey = `${key}/${realtimeChild}`;
|
|
182
|
+
|
|
183
|
+
realtimePlugin.subscribe(realtimeKey, refresh);
|
|
184
|
+
return realtimeKey;
|
|
185
|
+
}
|
|
186
|
+
});
|
|
187
|
+
return oldFn(i).then((ret) => {
|
|
188
|
+
if (subscribe) {
|
|
189
|
+
ret.subscribe = subscribe;
|
|
190
|
+
}
|
|
191
|
+
return ret;
|
|
192
|
+
});
|
|
193
|
+
};
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
if (onError) {
|
|
199
|
+
_onError = onError;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const NumPerPage = 200;
|
|
204
|
+
async function getAllPages<TRemote>(
|
|
205
|
+
listFn: (params: ListGetParams) => Promise<
|
|
206
|
+
APIResult<{
|
|
207
|
+
results: TRemote[];
|
|
208
|
+
pageInfo: any;
|
|
209
|
+
}>
|
|
210
|
+
>,
|
|
211
|
+
params: ListGetParams,
|
|
212
|
+
): Promise<{ results: TRemote[]; subscribe: (params: { refresh: () => void }) => string }> {
|
|
213
|
+
const allData: TRemote[] = [];
|
|
214
|
+
let pageInfo: PageInfo | undefined = undefined;
|
|
215
|
+
let subscribe_;
|
|
216
|
+
|
|
217
|
+
const { maxResults } = params;
|
|
218
|
+
|
|
219
|
+
do {
|
|
220
|
+
const first = maxResults ? Math.min(maxResults - allData.length, NumPerPage) : NumPerPage;
|
|
221
|
+
if (first < 1) {
|
|
222
|
+
break;
|
|
223
|
+
}
|
|
224
|
+
const pageEndCursor = pageInfo?.endCursor;
|
|
225
|
+
const paramsWithCursor: ListGetParams = pageEndCursor
|
|
226
|
+
? { first, ...params, after: pageEndCursor }
|
|
227
|
+
: { first, ...params };
|
|
228
|
+
pageInfo = undefined;
|
|
229
|
+
const ret = await listFn(paramsWithCursor);
|
|
230
|
+
|
|
231
|
+
if (ret) {
|
|
232
|
+
// @ts-expect-error TODOKEEL
|
|
233
|
+
const { data, error, subscribe } = ret;
|
|
234
|
+
|
|
235
|
+
if (subscribe) {
|
|
236
|
+
subscribe_ = subscribe;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
if (error) {
|
|
240
|
+
await handleApiError(error);
|
|
241
|
+
throw new Error(error.message);
|
|
242
|
+
} else if (data) {
|
|
243
|
+
pageInfo = data.pageInfo as PageInfo;
|
|
244
|
+
allData.push(...data.results);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
} while (pageInfo?.hasNextPage);
|
|
248
|
+
|
|
249
|
+
return { results: allData, subscribe: subscribe_ };
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
export function syncedKeel<TRemote extends { id: string }, TLocal = TRemote>(
|
|
253
|
+
props: SyncedKeelPropsBase<TRemote, TLocal> & SyncedKeelPropsSingle<TRemote, TLocal>,
|
|
254
|
+
): SyncedCrudReturnType<TLocal, 'first'>;
|
|
255
|
+
export function syncedKeel<TRemote extends { id: string }, TLocal = TRemote, TOption extends CrudAsOption = 'object'>(
|
|
256
|
+
props: SyncedKeelPropsBase<TRemote, TLocal> & SyncedKeelPropsMany<TRemote, TLocal, TOption>,
|
|
257
|
+
): SyncedCrudReturnType<TLocal, Exclude<TOption, 'first'>>;
|
|
258
|
+
export function syncedKeel<TRemote extends { id: string }, TLocal = TRemote, TOption extends CrudAsOption = 'object'>(
|
|
259
|
+
props: SyncedKeelPropsBase<TRemote, TLocal> &
|
|
260
|
+
(SyncedKeelPropsSingle<TRemote, TLocal> | SyncedKeelPropsMany<TRemote, TLocal, TOption>),
|
|
261
|
+
): SyncedCrudReturnType<TLocal, TOption> {
|
|
262
|
+
const {
|
|
263
|
+
get: getParam,
|
|
264
|
+
list: listParam,
|
|
265
|
+
create: createParam,
|
|
266
|
+
update: updateParam,
|
|
267
|
+
delete: deleteParam,
|
|
268
|
+
maxResults,
|
|
269
|
+
initial,
|
|
270
|
+
waitFor,
|
|
271
|
+
waitForSet,
|
|
272
|
+
...rest
|
|
273
|
+
} = props;
|
|
274
|
+
|
|
275
|
+
let asType = props.as as TOption;
|
|
276
|
+
|
|
277
|
+
if (!asType) {
|
|
278
|
+
asType = (getParam ? 'first' : _asOption || undefined) as TOption;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
let realtimeKeyList: string | undefined = undefined;
|
|
282
|
+
let realtimeKeyGet: string | undefined = undefined;
|
|
283
|
+
|
|
284
|
+
const fieldCreatedAt: KeelKey = 'createdAt';
|
|
285
|
+
const fieldUpdatedAt: KeelKey = 'updatedAt';
|
|
286
|
+
|
|
287
|
+
const list = listParam
|
|
288
|
+
? async (listParams: SyncedGetParams) => {
|
|
289
|
+
const { lastSync, refresh } = listParams;
|
|
290
|
+
const queryBySync = !!lastSync;
|
|
291
|
+
const isRawRequest = (listParam || getParam).toString().includes('rawRequest');
|
|
292
|
+
const where = queryBySync ? { updatedAt: { after: new Date(+new Date(lastSync) + 1) } } : {};
|
|
293
|
+
const params: ListGetParams = isRawRequest ? { where, maxResults } : { where, refresh, maxResults };
|
|
294
|
+
|
|
295
|
+
// TODO: Error?
|
|
296
|
+
const { results, subscribe } = await getAllPages(listParam, params);
|
|
297
|
+
if (!realtimeKeyList) {
|
|
298
|
+
realtimeKeyList = subscribe?.({ refresh });
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
return results;
|
|
302
|
+
}
|
|
303
|
+
: undefined;
|
|
304
|
+
|
|
305
|
+
const get = getParam
|
|
306
|
+
? async (getParams: SyncedGetParams) => {
|
|
307
|
+
const { refresh } = getParams;
|
|
308
|
+
// @ts-expect-error TODOKEEL
|
|
309
|
+
const { data, error, subscribe } = await getParam({ refresh });
|
|
310
|
+
if (!realtimeKeyGet) {
|
|
311
|
+
realtimeKeyGet = subscribe?.({ refresh });
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
if (error) {
|
|
315
|
+
throw new Error(error.message);
|
|
316
|
+
} else {
|
|
317
|
+
return data as TRemote;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
: undefined;
|
|
321
|
+
|
|
322
|
+
const onSaved = (data: TLocal, input: TRemote, isCreate: boolean): Partial<TLocal> | void => {
|
|
323
|
+
if (data) {
|
|
324
|
+
const savedOut: Partial<TLocal> = {};
|
|
325
|
+
if (isCreate) {
|
|
326
|
+
// Update with any fields that were undefined when creating
|
|
327
|
+
Object.keys(data).forEach((key) => {
|
|
328
|
+
if (input[key as keyof TRemote] === undefined) {
|
|
329
|
+
savedOut[key as keyof TLocal] = data[key as keyof TLocal];
|
|
330
|
+
}
|
|
331
|
+
});
|
|
332
|
+
} else {
|
|
333
|
+
// Update with any fields ending in createdAt or updatedAt
|
|
334
|
+
Object.keys(data).forEach((key) => {
|
|
335
|
+
const k = key as keyof TLocal;
|
|
336
|
+
const keyLower = key.toLowerCase();
|
|
337
|
+
if ((keyLower.endsWith('createdat') || keyLower.endsWith('updatedat')) && data[k] instanceof Date) {
|
|
338
|
+
savedOut[k] = data[k];
|
|
339
|
+
}
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
const updatedAt = data[fieldUpdatedAt as keyof TLocal] as Date;
|
|
344
|
+
|
|
345
|
+
if (updatedAt && _realtimePlugin) {
|
|
346
|
+
if (realtimeKeyGet) {
|
|
347
|
+
_realtimePlugin.setLatestChange(realtimeKeyGet, updatedAt);
|
|
348
|
+
}
|
|
349
|
+
if (realtimeKeyList) {
|
|
350
|
+
_realtimePlugin.setLatestChange(realtimeKeyList, updatedAt);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
return savedOut;
|
|
355
|
+
}
|
|
356
|
+
};
|
|
357
|
+
|
|
358
|
+
const handleSetError = async (error: APIError, params: SyncedSetParams<TRemote>, isCreate: boolean) => {
|
|
359
|
+
const { retryNum, cancelRetry, update } = params;
|
|
360
|
+
|
|
361
|
+
if (
|
|
362
|
+
isCreate &&
|
|
363
|
+
(error.message as string)?.includes('for the unique') &&
|
|
364
|
+
(error.message as string)?.includes('must be unique')
|
|
365
|
+
) {
|
|
366
|
+
if (__DEV__) {
|
|
367
|
+
console.log('Creating duplicate data already saved, just ignore.');
|
|
368
|
+
}
|
|
369
|
+
// This has already been saved but didn't update pending changes, so just update with {} to clear the pending state
|
|
370
|
+
update({
|
|
371
|
+
value: {},
|
|
372
|
+
mode: 'assign',
|
|
373
|
+
});
|
|
374
|
+
} else if (error.type === 'bad_request') {
|
|
375
|
+
_onError?.(error);
|
|
376
|
+
|
|
377
|
+
if (retryNum > 4) {
|
|
378
|
+
cancelRetry();
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
throw new Error(error.message);
|
|
382
|
+
} else {
|
|
383
|
+
await handleApiError(error);
|
|
384
|
+
|
|
385
|
+
throw new Error(error.message);
|
|
386
|
+
}
|
|
387
|
+
};
|
|
388
|
+
|
|
389
|
+
const create = createParam
|
|
390
|
+
? async (input: TRemote, params: SyncedSetParams<TRemote>) => {
|
|
391
|
+
const { data, error } = await createParam(convertObjectToCreate(input));
|
|
392
|
+
|
|
393
|
+
if (error) {
|
|
394
|
+
handleSetError(error, params, true);
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
return data;
|
|
398
|
+
}
|
|
399
|
+
: undefined;
|
|
400
|
+
|
|
401
|
+
const update = updateParam
|
|
402
|
+
? async (input: TRemote, params: SyncedSetParams<TRemote>) => {
|
|
403
|
+
const id = input.id;
|
|
404
|
+
const values = input as unknown as Partial<KeelObjectBase>;
|
|
405
|
+
delete values.id;
|
|
406
|
+
delete values.createdAt;
|
|
407
|
+
delete values.updatedAt;
|
|
408
|
+
|
|
409
|
+
const { data, error } = await updateParam({ where: { id }, values: input });
|
|
410
|
+
|
|
411
|
+
if (error) {
|
|
412
|
+
handleSetError(error, params, false);
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
return data;
|
|
416
|
+
}
|
|
417
|
+
: undefined;
|
|
418
|
+
const deleteFn = deleteParam
|
|
419
|
+
? async (input: TRemote & { id: string }, params: SyncedSetParams<TRemote>) => {
|
|
420
|
+
const { data, error } = await deleteParam({ id: input.id });
|
|
421
|
+
|
|
422
|
+
if (error) {
|
|
423
|
+
handleSetError(error, params, false);
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
return data;
|
|
427
|
+
}
|
|
428
|
+
: undefined;
|
|
429
|
+
|
|
430
|
+
return syncedCrud<TRemote, TLocal, TOption>({
|
|
431
|
+
...rest,
|
|
432
|
+
as: asType,
|
|
433
|
+
list,
|
|
434
|
+
create,
|
|
435
|
+
update,
|
|
436
|
+
delete: deleteFn,
|
|
437
|
+
retry: { infinite: true },
|
|
438
|
+
waitFor: () => isEnabled$.get() && (waitFor ? computeSelector(waitFor) : true),
|
|
439
|
+
waitForSet: () => isEnabled$.get() && (waitForSet ? computeSelector(waitForSet) : true),
|
|
440
|
+
onSaved,
|
|
441
|
+
fieldCreatedAt,
|
|
442
|
+
fieldUpdatedAt,
|
|
443
|
+
initial: initial as any, // This errors because of the get/list union type
|
|
444
|
+
// @ts-expect-error This errors because of the get/list union type
|
|
445
|
+
get: get as any,
|
|
446
|
+
}) as SyncedCrudReturnType<TLocal, TOption>;
|
|
447
|
+
}
|