-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathDocumentRootStore.ts
More file actions
466 lines (440 loc) · 16.7 KB
/
DocumentRootStore.ts
File metadata and controls
466 lines (440 loc) · 16.7 KB
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 { action, computed, observable, runInAction } from 'mobx';
import { RootStore } from '@tdev-stores/rootStore';
import { computedFn } from 'mobx-utils';
import DocumentRoot, { TypeMeta } from '@tdev-models/DocumentRoot';
import {
Config,
create as apiCreate,
DocumentRootUpdate,
remove as apiDelete,
findManyFor as apiFindManyFor,
update as apiUpdate,
DocumentRoot as ApiDocumentRoot
} from '@tdev-api/documentRoot';
import iStore from '@tdev-stores/iStore';
import GroupPermission from '@tdev-models/GroupPermission';
import UserPermission from '@tdev-models/UserPermission';
import { DocumentType } from '@tdev-api/document';
import _ from 'es-toolkit/compat';
import User from '@tdev-models/User';
import { NoneAccess } from '@tdev-models/helpers/accessPolicy';
import { ModelMeta as ProgressStateMeta } from '@tdev-models/documents/ProgressState';
import { CodeMeta } from '@tdev-models/documents/Code';
import { ModelMeta as MdxCommentMeta } from '@tdev-models/documents/MdxComment';
import { ModelMeta as RestrictedMeta } from '@tdev-models/documents/Restricted';
import { ModelMeta as SolutionMeta } from '@tdev-models/documents/Solution';
import { ModelMeta as StringMeta } from '@tdev-models/documents/String';
import { TaskMeta as TaskStateMeta } from '@tdev-models/documents/TaskState';
import { CmsTextMeta } from '@tdev-models/documents/CmsText';
type LoadConfig = {
/** if true, user permissions will be loaded
* @default true
*/
userPermissions?: boolean;
/**
* if true, group permissions will be loaded
* @default true
*/
groupPermissions?: boolean;
/**
* @option 'replace': the document root will be created and when already exists,
* it will replace the existing one.
* @option 'addIfMissing': when the document root does not exist in the mobx store, it will
* be added. But no new document root will be created on the api.
* @option false: the document root will not be loaded.
* @default 'replace'
*/
documentRoot?: 'replace' | 'addIfMissing' | boolean;
/**
* if a document root should not be created when it is not found,
* set `skipCreate` to true
* @default false
*/
skipCreate?: boolean;
/**
* if only document's of a specific type should be loaded
* @default undefined
*/
documentType?: DocumentType;
/**
* wheter documents linked to the document root should be added to the store
* @default true
*/
documents?: boolean;
};
type BatchedMeta = {
load: LoadConfig;
meta?: TypeMeta<any>;
access: Partial<Config>;
};
const DefaultMeta: TypeMeta<DocumentType>[] = [
new CodeMeta({}),
new MdxCommentMeta({}),
new RestrictedMeta({}),
new SolutionMeta({}),
new StringMeta({}),
new TaskStateMeta({}),
new ProgressStateMeta({}),
new CmsTextMeta({})
];
export class DocumentRootStore extends iStore {
readonly root: RootStore;
documentRoots = observable.array<DocumentRoot<DocumentType>>([]);
createAttempts = new Map<string, number>();
queued = new Map<string, BatchedMeta>();
constructor(root: RootStore) {
super();
this.root = root;
}
@computed
get hasApiAccess() {
return this.root.sessionStore.isLoggedIn;
}
@computed
get defaultMetas(): TypeMeta<DocumentType>[] {
return [...DefaultMeta, ...this.root.componentStore.defaultMeta];
}
@action
addDocumentRoot(
documentRoot: DocumentRoot<DocumentType>,
config: { cleanup?: boolean; deep?: boolean } = {}
) {
const old = this.find(documentRoot.id);
if (old) {
this.documentRoots.remove(old);
if (config.cleanup) {
this.cleanupDocumentRoot(old, config.deep);
}
}
this.documentRoots.push(documentRoot);
return documentRoot;
}
find = computedFn(
function <Type extends DocumentType = DocumentType>(
this: DocumentRootStore,
id?: string
): DocumentRoot<Type> | undefined {
if (!id) {
return;
}
return this.documentRoots.find((d) => d.id === id) as DocumentRoot<Type> | undefined;
},
{ keepAlive: true }
);
/**
*
* @param id documentRootId
* @param meta meta is only needed when you want to create a "default" document for this document root
* @returns
*/
@action
loadInNextBatch<Type extends DocumentType>(
id: string,
meta?: TypeMeta<Type>,
loadConfig?: LoadConfig,
accessConfig?: Partial<Config>
) {
if (this.queued.has(id)) {
const currentConfig = this.queued.get(id);
const needsReplacement =
loadConfig?.documentRoot === 'replace' && currentConfig?.load.documentRoot !== 'replace';
if (!needsReplacement) {
// already queued with same or higher loadConfig - do nothing
return;
}
}
this.queued.set(id, {
meta: meta,
load: {
documentRoot: 'replace',
groupPermissions: true,
userPermissions: true,
skipCreate: false,
documents: true,
...(loadConfig || {})
},
access: accessConfig || {}
});
this.loadQueued();
}
/**
* load the documentRoots only
* - after 20 ms of "silence" (=no further load-requests during this period)
* - or after 25ms have elapsed
*/
loadQueued = _.debounce(action(this._loadQueued), 25, {
leading: false,
trailing: true,
maxWait: 50
});
/**
* loads all queued documentRoots. When a document root was not found,
* it will be **created** (when the user is logged in).
*/
@action
_loadQueued() {
const userId = this.root.userStore.viewedUserId;
if (!userId || this.queued.size === 0) {
return;
}
const batch = [...this.queued];
this.queued.clear();
const currentBatch = new Map(batch);
/**
* if the user is not logged in, we can't load the documents
* so we just mark all queued documents as loaded
*/
if (!this.root.sessionStore.isLoggedIn) {
[...currentBatch.keys()].forEach((id) => {
const dummyModel = this.find(id);
if (dummyModel && dummyModel.isDummy) {
dummyModel.setLoaded();
}
});
return;
}
const isUserSwitched = this.root.userStore.isUserSwitched;
/**
* load all queued documents
*/
const rootIds = [...currentBatch.keys()].sort();
const idConfigs: [DocumentType | undefined, string[]][] = [];
const rootIdsWithDocs = rootIds.filter((id) => !currentBatch.get(id)!.load.documentType);
if (rootIdsWithDocs.length > 0) {
idConfigs.push([undefined, rootIdsWithDocs]);
}
rootIds
.filter((id) => currentBatch.get(id)!.load.documentType)
.reduce((acc, id) => {
const type = currentBatch.get(id)!.load.documentType;
const idx = acc.findIndex((item) => item[0] === type);
if (idx < 0) {
acc.push([type, [id]]);
} else {
acc[idx][1].push(id);
}
return acc;
}, idConfigs);
this.withAbortController(`load-queued-${rootIds.join('--')}`, async (signal) => {
const ignoreMissingRoots = isUserSwitched && rootIds.every((id) => this.find(id)?.isLoaded);
const models = await Promise.all(
idConfigs.map(([docType, ids]) => {
return apiFindManyFor(userId, ids, ignoreMissingRoots, docType, signal.signal).catch(
(e) => {
console.warn('Error loading document roots', e);
return { data: [] };
}
);
})
).then((results) => results.flatMap((r) => r.data));
runInAction(() => {
models.forEach((data) => {
const config = currentBatch.get(data.id);
if (!config) {
return;
}
this.addApiResultToStore(data, config);
currentBatch.delete(data.id);
});
});
if (!isUserSwitched) {
// create all missing root documents
const created = await Promise.all(
[...currentBatch.keys()]
.filter((id) => !this.find(id)?.isLoaded && !currentBatch.get(id)!.load.skipCreate)
.map((id) => {
const config = currentBatch.get(id);
if (config && config.meta) {
return this.create(id, config.meta, config.access).catch(() => {
// queue it up for loading later - the model was probably generated in the mean time?
if (this.createAttempts.has(id)) {
this.createAttempts.set(id, this.createAttempts.get(id)! + 1);
if (this.createAttempts.get(id)! >= 5) {
// prevent infinite loading cycle
return undefined;
}
} else {
this.createAttempts.set(id, 1);
}
this.loadInNextBatch(id, config.meta, config.load, config.access);
return Promise.resolve({ id: id });
});
}
return Promise.resolve(undefined);
})
);
// delete all created roots from the current map
created
.filter((docRoot) => !!docRoot)
.forEach((docRoot) => {
currentBatch.delete(docRoot.id);
});
}
// mark all remaining roots as loaded
runInAction(() => {
[...currentBatch.keys()].forEach((id) => {
const dummyModel = this.find(id);
if (dummyModel && dummyModel.isDummy) {
dummyModel.setLoaded();
}
});
});
});
}
@action
addApiResultToStore(data: ApiDocumentRoot, config: Omit<BatchedMeta, 'access'>) {
if (config.load.documentRoot === 'replace' && !config.meta) {
return;
}
const defaultType = data.documents[0]?.type;
const meta =
config.meta ||
(this.find(data.id)?.meta as TypeMeta<any>) ||
(defaultType ? this.defaultMetas.find((m) => m.type === defaultType) : undefined);
const documentRoot =
config.load.documentRoot && meta ? new DocumentRoot(data, meta, this) : this.find(data.id);
if (!documentRoot) {
return;
}
if (config.load.documentRoot) {
if (config.load.documentRoot === 'addIfMissing') {
if (!this.find(data.id)) {
this.addDocumentRoot(documentRoot);
}
} else {
this.addDocumentRoot(documentRoot, { cleanup: true, deep: false });
}
}
if (config.load.groupPermissions) {
data.groupPermissions.forEach((gp) => {
this.root.permissionStore.addGroupPermission(
new GroupPermission({ ...gp, documentRootId: documentRoot.id }, this.root.permissionStore)
);
});
}
if (config.load.userPermissions) {
data.userPermissions.forEach((up) => {
this.root.permissionStore.addUserPermission(
new UserPermission({ ...up, documentRootId: documentRoot.id }, this.root.permissionStore)
);
});
}
if (config.load.documents) {
data.documents.forEach((doc) => {
this.root.documentStore.addToStore(doc);
});
}
return documentRoot;
}
@action
create<Type extends DocumentType>(id: string, meta: TypeMeta<Type>, config: Partial<Config>) {
return this.withAbortController(`create-${id}`, async (signal) => {
const { data } = await apiCreate(id, config, signal.signal);
const docRoot = new DocumentRoot(data, meta, this);
this.addDocumentRoot(docRoot, { cleanup: true, deep: false });
return docRoot;
});
}
@action
handleUpdate({ id, access, sharedAccess }: DocumentRootUpdate) {
const model = this.find(id);
if (model && this.root.userStore.current) {
const old = model.permission;
let needsReload = false;
if (access !== model.rootAccess) {
model.setRootAccess(access);
const current = model.permission;
needsReload = NoneAccess.has(old) && !NoneAccess.has(current);
}
if (sharedAccess !== model.sharedAccess) {
needsReload =
needsReload || (NoneAccess.has(model.sharedAccess) && !NoneAccess.has(sharedAccess));
model.setSharedAccess(sharedAccess);
}
if (needsReload) {
this.reload(model);
console.log('reload model', model.id);
}
}
}
/**
* returns userPermissions and! groupPermissions
*/
usersPermissions(documentRootId: string, userId: string) {
const user = this.root.userStore.find(userId);
return this._permissionsByUser(documentRootId, user);
}
/**
* returns userPermissions and! groupPermissions
*/
currentUsersPermissions(documentRootId: string) {
const currentUser = this.root.userStore.current;
return this._permissionsByUser(documentRootId, currentUser);
}
/**
* returns userPermissions and! groupPermissions
*/
private _permissionsByUser(documentRootId: string, user?: User) {
if (!user) {
return [];
}
return this.root.permissionStore
.permissionsByDocumentRoot(documentRootId)
.filter((p) => p.isAffectingUser(user));
}
@action
removeFromStore(documentRootId: string, cleanup: boolean = true) {
const docRoot = this.find(documentRootId);
if (docRoot) {
this.documentRoots.remove(docRoot);
if (cleanup) {
this.cleanupDocumentRoot(docRoot);
}
}
}
@action
cleanupDocumentRoot(documentRoot: DocumentRoot<DocumentType>, cleanupDeep: boolean = true) {
documentRoot.documents.forEach((doc) => {
this.root.documentStore.removeFromStore(doc, cleanupDeep);
});
}
@action
reload(documentRoot: DocumentRoot<any>) {
this.loadInNextBatch(documentRoot.id, documentRoot.meta, {
documentRoot: 'replace',
documents: true,
groupPermissions: true,
userPermissions: true
});
}
@action
save(documentRoot: DocumentRoot<any>) {
if (!this.root.sessionStore.isLoggedIn || !this.root.userStore.current?.hasElevatedAccess) {
return Promise.resolve('error');
}
const model = {
access: documentRoot.rootAccess,
sharedAccess: documentRoot.sharedAccess
};
return this.withAbortController(`save-${documentRoot.id}`, (signal) => {
return apiUpdate(documentRoot.id, model, signal.signal);
}).catch(() => console.warn('Error saving document root'));
}
@action
destroy(documentRoot: DocumentRoot<any>) {
if (!this.root.sessionStore.isLoggedIn || !this.root.userStore.current?.hasElevatedAccess) {
return Promise.reject('error');
}
return this.withAbortController(`destroy-${documentRoot.id}`, (signal) => {
return apiDelete(documentRoot.id, signal.signal);
})
.then(() => {
this.removeFromStore(documentRoot.id);
return true;
})
.catch(() => {
console.warn('Error destroying document root');
return false;
});
}
}