-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
record-state.ts
466 lines (404 loc) · 11.8 KB
/
record-state.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
import { assert } from '@ember/debug';
import { dependentKeyCompat } from '@ember/object/compat';
import { DEBUG } from '@glimmer/env';
import { cached, tracked } from '@glimmer/tracking';
import type Store from '@ember-data/store';
import { storeFor } from '@ember-data/store';
import { recordIdentifierFor } from '@ember-data/store/-private';
import type { NotificationType } from '@ember-data/store/-private/managers/record-notification-manager';
import type RequestCache from '@ember-data/store/-private/network/request-cache';
import { addToTransaction, subscribe } from '@ember-data/tracking/-private';
import type { StableRecordIdentifier } from '@ember-data/types/q/identifier';
import type { RecordData } from '@ember-data/types/q/record-data';
type Model = InstanceType<typeof import('./model')>;
const SOURCE_POINTER_REGEXP = /^\/?data\/(attributes|relationships)\/(.*)/;
const SOURCE_POINTER_PRIMARY_REGEXP = /^\/?data/;
const PRIMARY_ATTRIBUTE_KEY = 'base';
function isInvalidError(error) {
return error && error.isAdapterError === true && error.code === 'InvalidError';
}
/**
* Tag provides a cache for a getter
* that recomputes only when a specific
* tracked property that it manages is dirtied.
*
* This allows us to bust the cache for a value
* that otherwise doesn't access anything tracked
* as well as control the timing of that notification.
*
* @internal
*/
class Tag {
declare rev: number;
declare isDirty: boolean;
declare value: any;
constructor() {
this.rev = 1;
this.isDirty = true;
this.value = undefined;
}
@tracked ref = null;
notify() {
this.isDirty = true;
addToTransaction(this);
this.rev++;
}
consume(v) {
this.isDirty = false;
this.value = v; // set cached value
}
}
const Tags = new WeakMap();
function getTag(record, key) {
let tags = Tags.get(record);
if (!tags) {
tags = Object.create(null);
Tags.set(record, tags);
}
return (tags[key] = tags[key] || new Tag());
}
export function peekTag(record, key) {
let tags = Tags.get(record);
return tags && tags[key];
}
/**
* A decorattor that caches a getter while
* providing the ability to bust that cache
* when we so choose in a way that notifies
* glimmer's tracking system.
*
* @internal
*/
export function tagged(_target, key, desc) {
const getter = desc.get;
const setter = desc.set;
desc.get = function () {
let tag = getTag(this, key);
subscribe(tag);
if (tag.isDirty) {
tag.consume(getter.call(this));
}
return tag.value;
};
desc.set = function (v) {
getTag(this, key); // ensure tag is setup in case we want to use it.
// probably notify here but not yet.
setter.call(this, v);
};
dependentKeyCompat(desc);
return desc;
}
/**
Historically EmberData managed a state machine
for each record, the localState for which
was reflected onto Model.
This implements the flags and stateName for backwards compat
with the state tree that used to be possible (listed below).
stateName and dirtyType are candidates for deprecation.
root
empty
deleted // hidden from stateName
preloaded // hidden from stateName
loading
empty // hidden from stateName
preloaded // hidden from stateName
loaded
saved
updated
uncommitted
invalid
inFlight
created
uncommitted
invalid
inFlight
deleted
saved
new // hidden from stateName
uncommitted
invalid
inFlight
@internal
*/
export default class RecordState {
declare store: Store;
declare identifier: StableRecordIdentifier;
declare record: Model;
declare rs: RequestCache;
declare pendingCount: number;
declare fulfilledCount: number;
declare rejectedCount: number;
declare recordData: RecordData;
declare _errorRequests: any[];
declare _lastError: any;
declare handler: object;
constructor(record: Model) {
const store = storeFor(record)!;
const identity = recordIdentifierFor(record);
this.identifier = identity;
this.record = record;
this.recordData = store._instanceCache.getRecordData(identity);
this.pendingCount = 0;
this.fulfilledCount = 0;
this.rejectedCount = 0;
this._errorRequests = [];
this._lastError = null;
let requests = store.getRequestStateService();
let notifications = store._notificationManager;
const handleRequest = (req) => {
if (req.type === 'mutation') {
switch (req.state) {
case 'pending':
this.isSaving = true;
break;
case 'rejected':
this.isSaving = false;
this._lastError = req;
if (!(req.response && isInvalidError(req.response.data))) {
this._errorRequests.push(req);
}
notifyErrorsStateChanged(this);
break;
case 'fulfilled':
this._errorRequests = [];
this._lastError = null;
this.isSaving = false;
notifyErrorsStateChanged(this);
break;
}
} else {
switch (req.state) {
case 'pending':
this.pendingCount++;
this.notify('isLoading');
break;
case 'rejected':
this.pendingCount--;
this._lastError = req;
if (!(req.response && isInvalidError(req.response.data))) {
this._errorRequests.push(req);
}
this.notify('isLoading');
notifyErrorsStateChanged(this);
break;
case 'fulfilled':
this.pendingCount--;
this.fulfilledCount++;
this.notify('isLoading');
this.notify('isDirty');
notifyErrorsStateChanged(this);
this._errorRequests = [];
this._lastError = null;
break;
}
}
};
requests.subscribeForRecord(identity, handleRequest);
// we instantiate lazily
// so we grab anything we don't have yet
if (!DEBUG) {
const lastRequest = requests.getLastRequestForRecord(identity);
if (lastRequest) {
handleRequest(lastRequest);
}
}
this.handler = notifications.subscribe(
identity,
(identifier: StableRecordIdentifier, type: NotificationType, key?: string) => {
switch (type) {
case 'state':
this.notify('isNew');
this.notify('isDeleted');
this.notify('isDirty');
break;
case 'attributes':
this.notify('isEmpty');
this.notify('isDirty');
break;
case 'errors':
this.updateInvalidErrors(this.record.errors);
this.notify('isValid');
break;
}
}
);
}
destroy() {
storeFor(this.record)!._notificationManager.unsubscribe(this.handler);
}
notify(key) {
getTag(this, key).notify();
}
updateInvalidErrors(errors) {
assert(
`Expected the RecordData instance for ${this.identifier} to implement getErrors(identifier)`,
typeof this.recordData.getErrors === 'function'
);
let jsonApiErrors = this.recordData.getErrors(this.identifier);
errors.clear();
for (let i = 0; i < jsonApiErrors.length; i++) {
let error = jsonApiErrors[i];
if (error.source && error.source.pointer) {
let keyMatch = error.source.pointer.match(SOURCE_POINTER_REGEXP);
let key: string | undefined;
if (keyMatch) {
key = keyMatch[2];
} else if (error.source.pointer.search(SOURCE_POINTER_PRIMARY_REGEXP) !== -1) {
key = PRIMARY_ATTRIBUTE_KEY;
}
if (key) {
let errMsg = error.detail || error.title;
errors.add(key, errMsg);
}
}
}
}
cleanErrorRequests() {
this.notify('isValid');
this.notify('isError');
this.notify('adapterError');
this._errorRequests = [];
this._lastError = null;
}
@tracked isSaving = false;
@tagged
get isLoading() {
return !this.isLoaded && this.pendingCount > 0 && this.fulfilledCount === 0;
}
@tagged
get isLoaded() {
if (this.isNew) {
return true;
}
return this.fulfilledCount > 0 || !this.isEmpty;
}
@tagged
get isSaved() {
let rd = this.recordData;
if (this.isDeleted) {
assert(`Expected RecordData to implement isDeletionCommitted()`, rd.isDeletionCommitted);
return rd.isDeletionCommitted(this.identifier);
}
if (this.isNew || this.isEmpty || !this.isValid || this.isDirty || this.isLoading) {
return false;
}
return true;
}
@tagged
get isEmpty() {
let rd = this.recordData;
// TODO this is not actually an RFC'd concept. Determine the
// correct heuristic to replace this with.
assert(`Expected RecordData to implement isEmpty()`, rd.isEmpty);
return !this.isNew && rd.isEmpty(this.identifier);
}
@tagged
get isNew() {
let rd = this.recordData;
assert(`Expected RecordData to implement isNew()`, rd.isNew);
return rd.isNew(this.identifier);
}
@tagged
get isDeleted() {
let rd = this.recordData;
assert(`Expected RecordData to implement isDeleted()`, rd.isDeleted);
return rd.isDeleted(this.identifier);
}
@tagged
get isValid() {
return this.record.errors.length === 0;
}
@tagged
get isDirty() {
let rd = this.recordData;
if (rd.isDeletionCommitted(this.identifier) || (this.isDeleted && this.isNew)) {
return false;
}
return this.isNew || rd.hasChangedAttrs(this.identifier);
}
@tagged
get isError() {
let errorReq = this._errorRequests[this._errorRequests.length - 1];
if (!errorReq) {
return false;
} else {
return true;
}
}
@tagged
get adapterError() {
let request = this._lastError;
if (!request) {
return null;
}
return request.state === 'rejected' && request.response.data;
}
@cached
get isPreloaded() {
return !this.isEmpty && this.isLoading;
}
@cached
get stateName() {
// we might be empty while loading so check this first
if (this.isLoading) {
return 'root.loading';
// got nothing yet or were unloaded
} else if (this.isEmpty) {
return 'root.empty';
// deleted substates
} else if (this.isDeleted) {
if (this.isSaving) {
return 'root.deleted.inFlight';
} else if (this.isSaved) {
// TODO ensure isSaved isn't true from previous requests
return 'root.deleted.saved';
} else if (!this.isValid) {
return 'root.deleted.invalid';
} else {
return 'root.deleted.uncommitted';
}
// loaded.created substates
} else if (this.isNew) {
if (this.isSaving) {
return 'root.loaded.created.inFlight';
} else if (!this.isValid) {
return 'root.loaded.created.invalid';
}
return 'root.loaded.created.uncommitted';
// loaded.updated substates
} else if (this.isSaving) {
return 'root.loaded.updated.inFlight';
} else if (!this.isValid) {
return 'root.loaded.updated.invalid';
} else if (this.isDirty) {
return 'root.loaded.updated.uncommitted';
// if nothing remains, we are loaded saved!
} else {
return 'root.loaded.saved';
}
}
@cached
get dirtyType() {
// we might be empty while loading so check this first
if (this.isLoading || this.isEmpty) {
return '';
// deleted substates
} else if (this.isDeleted) {
return 'deleted';
// loaded.created substates
} else if (this.isNew) {
return 'created';
// loaded.updated substates
} else if (this.isSaving || !this.isValid || this.isDirty) {
return 'updated';
// if nothing remains, we are loaded saved!
} else {
return '';
}
}
}
function notifyErrorsStateChanged(state: RecordState) {
state.notify('isValid');
state.notify('isError');
state.notify('adapterError');
}