/
schemas.service.ts
672 lines (550 loc) · 23.4 KB
/
schemas.service.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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
/*
* Squidex Headless CMS
*
* @license
* Copyright (c) Squidex UG (haftungsbeschränkt). All rights reserved.
*/
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { map, tap } from 'rxjs/operators';
import {
AnalyticsService,
ApiUrlConfig,
DateTime,
hasAnyLink,
HTTP,
pretifyError,
Resource,
ResourceLinks,
StringHelper,
Types,
Version,
Versioned
} from '@app/framework';
import { createProperties, FieldPropertiesDto } from './schemas.types';
export type SchemasDto = {
readonly items: ReadonlyArray<SchemaDto>;
readonly canCreate: boolean;
} & Resource;
export class SchemaDto {
public readonly _links: ResourceLinks;
public readonly canAddField: boolean;
public readonly canDelete: boolean;
public readonly canOrderFields: boolean;
public readonly canPublish: boolean;
public readonly canReadContents: boolean;
public readonly canSynchronize: boolean;
public readonly canUnpublish: boolean;
public readonly canUpdate: boolean;
public readonly canUpdateCategory: boolean;
public readonly canUpdateScripts: boolean;
public readonly canUpdateUrls: boolean;
public readonly displayName: string;
constructor(links: ResourceLinks,
public readonly id: string,
public readonly name: string,
public readonly category: string,
public readonly properties: SchemaPropertiesDto,
public readonly isSingleton: boolean,
public readonly isPublished: boolean,
public readonly created: DateTime,
public readonly createdBy: string,
public readonly lastModified: DateTime,
public readonly lastModifiedBy: string,
public readonly version: Version
) {
this._links = links;
this.canAddField = hasAnyLink(links, 'fields/add');
this.canDelete = hasAnyLink(links, 'delete');
this.canOrderFields = hasAnyLink(links, 'fields/order');
this.canPublish = hasAnyLink(links, 'publish');
this.canReadContents = hasAnyLink(links, 'contents');
this.canSynchronize = hasAnyLink(this, 'update/sync');
this.canUnpublish = hasAnyLink(links, 'unpublish');
this.canUpdate = hasAnyLink(links, 'update');
this.canUpdateCategory = hasAnyLink(links, 'update/category');
this.canUpdateScripts = hasAnyLink(links, 'update/scripts');
this.canUpdateUrls = hasAnyLink(links, 'update/urls');
this.displayName = StringHelper.firstNonEmpty(this.properties.label, this.name);
}
}
export class SchemaDetailsDto extends SchemaDto {
public readonly listFields: ReadonlyArray<RootFieldDto>;
public readonly listFieldsEditable: ReadonlyArray<RootFieldDto>;
public readonly referenceFields: ReadonlyArray<RootFieldDto>;
constructor(links: ResourceLinks, id: string, name: string, category: string,
properties: SchemaPropertiesDto,
isSingleton: boolean,
isPublished: boolean,
created: DateTime,
createdBy: string,
lastModified: DateTime,
lastModifiedBy: string,
version: Version,
public readonly fields: ReadonlyArray<RootFieldDto> = [],
public readonly scripts = {},
public readonly previewUrls = {}
) {
super(links, id, name, category, properties, isSingleton, isPublished, created, createdBy, lastModified, lastModifiedBy, version);
if (fields) {
this.listFields = this.fields.filter(x => x.properties.isListField && x.properties.isContentField);
if (this.listFields.length === 0 && this.fields.length > 0) {
this.listFields = [this.fields[0]];
}
if (this.listFields.length === 0) {
this.listFields = NONE_FIELDS;
}
this.listFieldsEditable = this.listFields.filter(x => x.isInlineEditable);
this.referenceFields = this.fields.filter(x => x.properties.isReferenceField && x.properties.isContentField);
if (this.referenceFields.length === 0) {
this.referenceFields = this.listFields;
}
}
}
public export(): any {
const fieldKeys = ['fieldId', '_links', 'parentFieldId'];
const cleanup = (source: any, ...exclude: string[]): any => {
const clone = {};
for (const key in source) {
if (source.hasOwnProperty(key) && exclude.indexOf(key) < 0 && key.indexOf('can') !== 0) {
const value = source[key];
if (value) {
clone[key] = value;
}
}
}
return clone;
};
const result: any = {
fields: this.fields.map(field => {
const copy = cleanup(field, ...fieldKeys);
copy.properties = cleanup(field.properties);
if (Types.isArray(copy.nested)) {
if (copy.nested.length === 0) {
delete copy['nested'];
} else {
copy.nested = field.nested.map(nestedField => {
const nestedCopy = cleanup(nestedField, ...fieldKeys);
nestedCopy.properties = cleanup(nestedField.properties);
return nestedCopy;
});
}
}
return copy;
}),
properties: cleanup(this.properties)
};
return result;
}
}
export class FieldDto {
public readonly _links: ResourceLinks;
public readonly canAddField: boolean;
public readonly canDelete: boolean;
public readonly canDisable: boolean;
public readonly canEnable: boolean;
public readonly canHide: boolean;
public readonly canLock: boolean;
public readonly canOrderFields: boolean;
public readonly canShow: boolean;
public readonly canUpdate: boolean;
public get isInlineEditable(): boolean {
return !this.isDisabled && this.rawProperties.inlineEditable === true;
}
public get displayName() {
return StringHelper.firstNonEmpty(this.properties.label, this.name);
}
public get displayPlaceholder() {
return this.properties.placeholder || '';
}
public get rawProperties(): any {
return this.properties;
}
constructor(links: ResourceLinks,
public readonly fieldId: number,
public readonly name: string,
public readonly properties: FieldPropertiesDto,
public readonly isLocked: boolean = false,
public readonly isHidden: boolean = false,
public readonly isDisabled: boolean = false
) {
this._links = links;
this.canAddField = hasAnyLink(links, 'fields/add');
this.canDelete = hasAnyLink(links, 'delete');
this.canDisable = hasAnyLink(links, 'disable');
this.canEnable = hasAnyLink(links, 'enable');
this.canOrderFields = hasAnyLink(links, 'fields/order');
this.canHide = hasAnyLink(links, 'hide');
this.canLock = hasAnyLink(links, 'lock');
this.canShow = hasAnyLink(links, 'show');
this.canUpdate = hasAnyLink(links, 'update');
}
}
export class RootFieldDto extends FieldDto {
public get isLocalizable() {
return this.partitioning === 'language';
}
public get isArray() {
return this.properties.fieldType === 'Array';
}
public get isTranslatable() {
return this.isLocalizable && this.properties.isTranslateable;
}
constructor(links: ResourceLinks, fieldId: number, name: string, properties: FieldPropertiesDto,
public readonly partitioning: string,
isLocked: boolean = false,
isHidden: boolean = false,
isDisabled: boolean = false,
public readonly nested: ReadonlyArray<NestedFieldDto> = []
) {
super(links, fieldId, name, properties, isLocked, isHidden, isDisabled);
}
}
const NONE_FIELD = new RootFieldDto({}, -1, '', createProperties('String'), 'invariant');
const NONE_FIELDS: ReadonlyArray<any> = [NONE_FIELD];
export class NestedFieldDto extends FieldDto {
constructor(links: ResourceLinks, fieldId: number, name: string, properties: FieldPropertiesDto,
public readonly parentId: number,
isLocked: boolean = false,
isHidden: boolean = false,
isDisabled: boolean = false
) {
super(links, fieldId, name, properties, isLocked, isHidden, isDisabled);
}
}
export class SchemaPropertiesDto {
constructor(
public readonly label?: string,
public readonly hints?: string,
public readonly tags?: ReadonlyArray<string>
) {
}
}
export interface AddFieldDto {
readonly name: string;
readonly partitioning?: string;
readonly properties: FieldPropertiesDto;
}
export interface CreateSchemaDto {
readonly name: string;
readonly fields?: ReadonlyArray<RootFieldDto>;
readonly properties?: SchemaPropertiesDto;
readonly isSingleton?: boolean;
}
export interface UpdateSchemaCategoryDto {
readonly name?: string;
}
export interface UpdateFieldDto {
readonly properties: FieldPropertiesDto;
}
export interface SynchronizeSchemaDto {
noFieldDeletiong?: boolean;
noFieldRecreation?: boolean;
}
export interface UpdateSchemaDto {
readonly label?: string;
readonly hints?: string;
}
@Injectable()
export class SchemasService {
constructor(
private readonly http: HttpClient,
private readonly apiUrl: ApiUrlConfig,
private readonly analytics: AnalyticsService
) {
}
public getSchemas(appName: string): Observable<SchemasDto> {
const url = this.apiUrl.buildUrl(`api/apps/${appName}/schemas`);
return HTTP.getVersioned(this.http, url).pipe(
map(({ payload }) => {
return parseSchemas(payload.body);
}),
pretifyError('Failed to load schemas. Please reload.'));
}
public getSchema(appName: string, name: string): Observable<SchemaDetailsDto> {
const url = this.apiUrl.buildUrl(`api/apps/${appName}/schemas/${name}`);
return HTTP.getVersioned(this.http, url).pipe(
map(({ payload }) => {
return parseSchemaWithDetails(payload.body);
}),
pretifyError('Failed to load schema. Please reload.'));
}
public postSchema(appName: string, dto: CreateSchemaDto): Observable<SchemaDetailsDto> {
const url = this.apiUrl.buildUrl(`api/apps/${appName}/schemas`);
return HTTP.postVersioned(this.http, url, dto).pipe(
map(({ payload }) => {
return parseSchemaWithDetails(payload.body);
}),
tap(() => {
this.analytics.trackEvent('Schema', 'Created', appName);
}),
pretifyError('Failed to create schema. Please reload.'));
}
public putScripts(appName: string, resource: Resource, dto: {}, version: Version): Observable<SchemaDetailsDto> {
const link = resource._links['update/scripts'];
const url = this.apiUrl.buildUrl(link.href);
return HTTP.requestVersioned(this.http, link.method, url, version, dto).pipe(
map(({ payload }) => {
return parseSchemaWithDetails(payload.body);
}),
tap(() => {
this.analytics.trackEvent('Schema', 'ScriptsConfigured', appName);
}),
pretifyError('Failed to update schema scripts. Please reload.'));
}
public putSchemaSync(appName: string, resource: Resource, dto: SynchronizeSchemaDto & any, version: Version): Observable<SchemaDetailsDto> {
const link = resource._links['update/sync'];
const url = this.apiUrl.buildUrl(link.href);
return HTTP.requestVersioned(this.http, link.method, url, version, dto).pipe(
map(({ payload }) => {
return parseSchemaWithDetails(payload.body);
}),
tap(() => {
this.analytics.trackEvent('Schema', 'Updated', appName);
}),
pretifyError('Failed to synchronize schema. Please reload.'));
}
public putSchema(appName: string, resource: Resource, dto: UpdateSchemaDto, version: Version): Observable<SchemaDetailsDto> {
const link = resource._links['update'];
const url = this.apiUrl.buildUrl(link.href);
return HTTP.requestVersioned(this.http, link.method, url, version, dto).pipe(
map(({ payload }) => {
return parseSchemaWithDetails(payload.body);
}),
tap(() => {
this.analytics.trackEvent('Schema', 'Updated', appName);
}),
pretifyError('Failed to update schema. Please reload.'));
}
public putCategory(appName: string, resource: Resource, dto: UpdateSchemaCategoryDto, version: Version): Observable<SchemaDetailsDto> {
const link = resource._links['update/category'];
const url = this.apiUrl.buildUrl(link.href);
return HTTP.requestVersioned(this.http, link.method, url, version, dto).pipe(
map(({ payload }) => {
return parseSchemaWithDetails(payload.body);
}),
tap(() => {
this.analytics.trackEvent('Schema', 'CategoryChanged', appName);
}),
pretifyError('Failed to change category. Please reload.'));
}
public putPreviewUrls(appName: string, resource: Resource, dto: {}, version: Version): Observable<SchemaDetailsDto> {
const link = resource._links['update/urls'];
const url = this.apiUrl.buildUrl(link.href);
return HTTP.requestVersioned(this.http, link.method, url, version, dto).pipe(
map(({ payload }) => {
return parseSchemaWithDetails(payload.body);
}),
tap(() => {
this.analytics.trackEvent('Schema', 'PreviewUrlsConfigured', appName);
}),
pretifyError('Failed to configure preview urls. Please reload.'));
}
public publishSchema(appName: string, resource: Resource, version: Version): Observable<SchemaDetailsDto> {
const link = resource._links['publish'];
const url = this.apiUrl.buildUrl(link.href);
return HTTP.requestVersioned(this.http, link.method, url, version, {}).pipe(
map(({ payload }) => {
return parseSchemaWithDetails(payload.body);
}),
tap(() => {
this.analytics.trackEvent('Schema', 'Published', appName);
}),
pretifyError('Failed to publish schema. Please reload.'));
}
public unpublishSchema(appName: string, resource: Resource, version: Version): Observable<SchemaDetailsDto> {
const link = resource._links['unpublish'];
const url = this.apiUrl.buildUrl(link.href);
return HTTP.requestVersioned(this.http, link.method, url, version, {}).pipe(
map(({ payload }) => {
return parseSchemaWithDetails(payload.body);
}),
tap(() => {
this.analytics.trackEvent('Schema', 'Unpublished', appName);
}),
pretifyError('Failed to unpublish schema. Please reload.'));
}
public postField(appName: string, resource: Resource, dto: AddFieldDto, version: Version): Observable<SchemaDetailsDto> {
const link = resource._links['fields/add'];
const url = this.apiUrl.buildUrl(link.href);
return HTTP.requestVersioned(this.http, link.method, url, version, dto).pipe(
map(({ payload }) => {
return parseSchemaWithDetails(payload.body);
}),
tap(() => {
this.analytics.trackEvent('Schema', 'FieldCreated', appName);
}),
pretifyError('Failed to add field. Please reload.'));
}
public putFieldOrdering(appName: string, resource: Resource, dto: ReadonlyArray<number>, version: Version): Observable<SchemaDetailsDto> {
const link = resource._links['fields/order'];
const url = this.apiUrl.buildUrl(link.href);
return HTTP.requestVersioned(this.http, link.method, url, version, { fieldIds: dto }).pipe(
map(({ payload }) => {
return parseSchemaWithDetails(payload.body);
}),
tap(() => {
this.analytics.trackEvent('Schema', 'FieldsReordered', appName);
}),
pretifyError('Failed to reorder fields. Please reload.'));
}
public putField(appName: string, resource: Resource, dto: UpdateFieldDto, version: Version): Observable<SchemaDetailsDto> {
const link = resource._links['update'];
const url = this.apiUrl.buildUrl(link.href);
return HTTP.requestVersioned(this.http, link.method, url, version, dto).pipe(
map(({ payload }) => {
return parseSchemaWithDetails(payload.body);
}),
tap(() => {
this.analytics.trackEvent('Schema', 'FieldUpdated', appName);
}),
pretifyError('Failed to update field. Please reload.'));
}
public lockField(appName: string, resource: Resource, version: Version): Observable<SchemaDetailsDto> {
const link = resource._links['lock'];
const url = this.apiUrl.buildUrl(link.href);
return HTTP.requestVersioned(this.http, link.method, url, version, {}).pipe(
map(({ payload }) => {
return parseSchemaWithDetails(payload.body);
}),
tap(() => {
this.analytics.trackEvent('Schema', 'FieldLocked', appName);
}),
pretifyError('Failed to lock field. Please reload.'));
}
public enableField(appName: string, resource: Resource, version: Version): Observable<SchemaDetailsDto> {
const link = resource._links['enable'];
const url = this.apiUrl.buildUrl(link.href);
return HTTP.requestVersioned(this.http, link.method, url, version, {}).pipe(
map(({ payload }) => {
return parseSchemaWithDetails(payload.body);
}),
tap(() => {
this.analytics.trackEvent('Schema', 'FieldEnabled', appName);
}),
pretifyError('Failed to enable field. Please reload.'));
}
public disableField(appName: string, resource: Resource, version: Version): Observable<SchemaDetailsDto> {
const link = resource._links['disable'];
const url = this.apiUrl.buildUrl(link.href);
return HTTP.requestVersioned(this.http, link.method, url, version, {}).pipe(
map(({ payload }) => {
return parseSchemaWithDetails(payload.body);
}),
tap(() => {
this.analytics.trackEvent('Schema', 'FieldDisabled', appName);
}),
pretifyError('Failed to disable field. Please reload.'));
}
public showField(appName: string, resource: Resource, version: Version): Observable<SchemaDetailsDto> {
const link = resource._links['show'];
const url = this.apiUrl.buildUrl(link.href);
return HTTP.requestVersioned(this.http, link.method, url, version, {}).pipe(
map(({ payload }) => {
return parseSchemaWithDetails(payload.body);
}),
tap(() => {
this.analytics.trackEvent('Schema', 'FieldShown', appName);
}),
pretifyError('Failed to show field. Please reload.'));
}
public hideField(appName: string, resource: Resource, version: Version): Observable<SchemaDetailsDto> {
const link = resource._links['hide'];
const url = this.apiUrl.buildUrl(link.href);
return HTTP.requestVersioned(this.http, link.method, url, version, {}).pipe(
map(({ payload }) => {
return parseSchemaWithDetails(payload.body);
}),
tap(() => {
this.analytics.trackEvent('Schema', 'FieldHidden', appName);
}),
pretifyError('Failed to hide field. Please reload.'));
}
public deleteField(appName: string, resource: Resource, version: Version): Observable<SchemaDetailsDto> {
const link = resource._links['delete'];
const url = this.apiUrl.buildUrl(link.href);
return HTTP.requestVersioned(this.http, link.method, url, version, {}).pipe(
map(({ payload }) => {
return parseSchemaWithDetails(payload.body);
}),
tap(() => {
this.analytics.trackEvent('Schema', 'FieldDeleted', appName);
}),
pretifyError('Failed to delete field. Please reload.'));
}
public deleteSchema(appName: string, resource: Resource, version: Version): Observable<Versioned<any>> {
const link = resource._links['delete'];
const url = this.apiUrl.buildUrl(link.href);
return HTTP.requestVersioned(this.http, link.method, url, version).pipe(
tap(() => {
this.analytics.trackEvent('Schema', 'Deleted', appName);
}),
pretifyError('Failed to delete schema. Please reload.'));
}
}
function parseSchemas(response: any) {
const raw: any[] = response.items;
const items = raw.map(item =>
new SchemaDto(item._links,
item.id,
item.name,
item.category,
new SchemaPropertiesDto(item.properties.label, item.properties.hints, item.properties.tags),
item.isSingleton,
item.isPublished,
DateTime.parseISO_UTC(item.created), item.createdBy,
DateTime.parseISO_UTC(item.lastModified), item.lastModifiedBy,
new Version(item.version.toString())));
const _links = response._links;
return { items, _links, canCreate: hasAnyLink(_links, 'create') };
}
function parseSchemaWithDetails(response: any) {
const fields = response.fields.map((item: any) => parseField(item));
const properties = new SchemaPropertiesDto(response.properties.label, response.properties.hints, response.properties.tags);
return new SchemaDetailsDto(response._links,
response.id,
response.name,
response.category,
properties,
response.isSingleton,
response.isPublished,
DateTime.parseISO_UTC(response.created), response.createdBy,
DateTime.parseISO_UTC(response.lastModified), response.lastModifiedBy,
new Version(response.version.toString()),
fields,
response.scripts || {},
response.previewUrls || {});
}
export function parseField(item: any) {
const propertiesDto =
createProperties(
item.properties.fieldType,
item.properties);
let nested: NestedFieldDto[] | null = null;
if (item.nested && item.nested.length > 0) {
nested = item.nested.map((nestedItem: any) => {
const nestedPropertiesDto =
createProperties(
nestedItem.properties.fieldType,
nestedItem.properties);
return new NestedFieldDto(nestedItem._links,
nestedItem.fieldId,
nestedItem.name,
nestedPropertiesDto,
item.fieldId,
nestedItem.isLocked,
nestedItem.isHidden,
nestedItem.isDisabled);
});
}
return new RootFieldDto(item._links,
item.fieldId,
item.name,
propertiesDto,
item.partitioning,
item.isLocked,
item.isHidden,
item.isDisabled,
nested || []);
}