-
-
Notifications
You must be signed in to change notification settings - Fork 144
Expand file tree
/
Copy pathrest-generator.ts
More file actions
1058 lines (973 loc) · 39.8 KB
/
rest-generator.ts
File metadata and controls
1058 lines (973 loc) · 39.8 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
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
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Inspired by: https://github.com/omar-dulaimi/prisma-trpc-generator
import {
analyzePolicies,
getDataModels,
hasAttribute,
isForeignKeyField,
isIdField,
isRelationshipField,
PluginError,
PluginOptions,
requireOption,
resolvePath,
} from '@zenstackhq/sdk';
import {
DataModel,
DataModelField,
DataModelFieldType,
Enum,
isDataModel,
isEnum,
isTypeDef,
Model,
TypeDef,
TypeDefField,
TypeDefFieldType,
} from '@zenstackhq/sdk/ast';
import type { DMMF } from '@zenstackhq/sdk/prisma';
import fs from 'fs';
import { lowerCaseFirst } from 'lower-case-first';
import type { OpenAPIV3_1 as OAPI } from 'openapi-types';
import path from 'path';
import pluralize from 'pluralize';
import invariant from 'tiny-invariant';
import { match, P } from 'ts-pattern';
import YAML from 'yaml';
import { name } from '.';
import { OpenAPIGeneratorBase } from './generator-base';
import { getModelResourceMeta } from './meta';
type Policies = ReturnType<typeof analyzePolicies>;
/**
* Generates RESTful style OpenAPI specification.
*/
export class RESTfulOpenAPIGenerator extends OpenAPIGeneratorBase {
private warnings: string[] = [];
constructor(protected model: Model, protected options: PluginOptions, protected dmmf: DMMF.Document) {
super(model, options, dmmf);
if (this.options.omitInputDetails !== undefined) {
throw new PluginError(name, '"omitInputDetails" option is not supported for "rest" flavor');
}
}
generate() {
let output = requireOption<string>(this.options, 'output', name);
output = resolvePath(output, this.options);
const components = this.generateComponents();
const paths = this.generatePaths();
// prune unused component schemas
this.pruneComponents(paths, components);
// generate security schemes, and root-level security
components.securitySchemes = this.generateSecuritySchemes();
let security: OAPI.Document['security'] | undefined = undefined;
if (components.securitySchemes && Object.keys(components.securitySchemes).length > 0) {
security = Object.keys(components.securitySchemes).map((scheme) => ({ [scheme]: [] }));
}
const openapi: OAPI.Document = {
openapi: this.getOption('specVersion', this.DEFAULT_SPEC_VERSION),
info: {
title: this.getOption('title', 'ZenStack Generated API'),
version: this.getOption('version', '1.0.0'),
description: this.getOption('description'),
summary: this.getOption('summary'),
},
tags: this.includedModels.map((model) => {
const meta = getModelResourceMeta(model);
return {
name: lowerCaseFirst(model.name),
description: meta?.tagDescription ?? `${model.name} operations`,
};
}),
paths,
components,
security,
};
const ext = path.extname(output);
if (ext && (ext.toLowerCase() === '.yaml' || ext.toLowerCase() === '.yml')) {
fs.writeFileSync(output, YAML.stringify(openapi));
} else {
fs.writeFileSync(output, JSON.stringify(openapi, undefined, 2));
}
return { warnings: this.warnings };
}
private generatePaths(): OAPI.PathsObject {
let result: OAPI.PathsObject = {};
const includeModelNames = this.includedModels.map((d) => d.name);
for (const model of this.dmmf.datamodel.models) {
if (includeModelNames.includes(model.name)) {
const zmodel = this.model.declarations.find(
(d) => isDataModel(d) && d.name === model.name
) as DataModel;
if (zmodel) {
result = {
...result,
...this.generatePathsForModel(model, zmodel),
} as OAPI.PathsObject;
} else {
this.warnings.push(`Unable to load ZModel definition for: ${model.name}}`);
}
}
}
return result;
}
private generatePathsForModel(model: DMMF.Model, zmodel: DataModel): OAPI.PathItemObject | undefined {
const result: Record<string, OAPI.PathItemObject> = {};
// analyze access policies to determine default security
const policies = analyzePolicies(zmodel);
let prefix = this.getOption('prefix', '');
if (prefix.endsWith('/')) {
prefix = prefix.substring(0, prefix.length - 1);
}
const resourceMeta = getModelResourceMeta(zmodel);
// GET /resource
// POST /resource
result[`${prefix}/${lowerCaseFirst(model.name)}`] = {
get: this.makeResourceList(zmodel, policies, resourceMeta),
post: this.makeResourceCreate(zmodel, policies, resourceMeta),
};
// GET /resource/{id}
// PUT /resource/{id}
// PATCH /resource/{id}
// DELETE /resource/{id}
result[`${prefix}/${lowerCaseFirst(model.name)}/{id}`] = {
get: this.makeResourceFetch(zmodel, policies, resourceMeta),
put: this.makeResourceUpdate(zmodel, policies, `update-${model.name}-put`, resourceMeta),
patch: this.makeResourceUpdate(zmodel, policies, `update-${model.name}-patch`, resourceMeta),
delete: this.makeResourceDelete(zmodel, policies, resourceMeta),
};
// paths for related resources and relationships
for (const field of zmodel.fields) {
const relationDecl = field.type.reference?.ref;
if (!isDataModel(relationDecl)) {
continue;
}
// GET /resource/{id}/{relationship}
const relatedDataPath = `${prefix}/${lowerCaseFirst(model.name)}/{id}/${field.name}`;
let container = result[relatedDataPath];
if (!container) {
container = result[relatedDataPath] = {};
}
container.get = this.makeRelatedFetch(zmodel, field, relationDecl, resourceMeta);
const relationshipPath = `${prefix}/${lowerCaseFirst(model.name)}/{id}/relationships/${field.name}`;
container = result[relationshipPath];
if (!container) {
container = result[relationshipPath] = {};
}
// GET /resource/{id}/relationships/{relationship}
container.get = this.makeRelationshipFetch(zmodel, field, policies, resourceMeta);
// PUT /resource/{id}/relationships/{relationship}
container.put = this.makeRelationshipUpdate(
zmodel,
field,
policies,
`update-${model.name}-relationship-${field.name}-put`,
resourceMeta
);
// PATCH /resource/{id}/relationships/{relationship}
container.patch = this.makeRelationshipUpdate(
zmodel,
field,
policies,
`update-${model.name}-relationship-${field.name}-patch`,
resourceMeta
);
if (field.type.array) {
// POST /resource/{id}/relationships/{relationship}
container.post = this.makeRelationshipCreate(zmodel, field, policies, resourceMeta);
}
}
return result;
}
private makeResourceList(model: DataModel, policies: Policies, resourceMeta: { security?: object } | undefined) {
return {
operationId: `list-${model.name}`,
description: `List "${model.name}" resources`,
tags: [lowerCaseFirst(model.name)],
parameters: [
this.parameter('include'),
this.parameter('sort'),
this.parameter('page-offset'),
this.parameter('page-limit'),
...this.generateFilterParameters(model),
],
responses: {
'200': this.success(`${model.name}ListResponse`),
'403': this.forbidden(),
},
security: resourceMeta?.security ?? policies.read === true ? [] : undefined,
};
}
private makeResourceCreate(model: DataModel, policies: Policies, resourceMeta: { security?: object } | undefined) {
return {
operationId: `create-${model.name}`,
description: `Create a "${model.name}" resource`,
tags: [lowerCaseFirst(model.name)],
requestBody: {
content: {
'application/vnd.api+json': {
schema: this.ref(`${model.name}CreateRequest`),
},
},
},
responses: {
'201': this.success(`${model.name}Response`),
'403': this.forbidden(),
'422': this.validationError(),
},
security: resourceMeta?.security ?? policies.create === true ? [] : undefined,
};
}
private makeResourceFetch(model: DataModel, policies: Policies, resourceMeta: { security?: object } | undefined) {
return {
operationId: `fetch-${model.name}`,
description: `Fetch a "${model.name}" resource`,
tags: [lowerCaseFirst(model.name)],
parameters: [this.parameter('id'), this.parameter('include')],
responses: {
'200': this.success(`${model.name}Response`),
'403': this.forbidden(),
'404': this.notFound(),
},
security: resourceMeta?.security ?? policies.read === true ? [] : undefined,
};
}
private makeRelatedFetch(
model: DataModel,
field: DataModelField,
relationDecl: DataModel,
resourceMeta: { security?: object } | undefined
) {
const policies = analyzePolicies(relationDecl);
const parameters: OAPI.OperationObject['parameters'] = [this.parameter('id'), this.parameter('include')];
if (field.type.array) {
parameters.push(
this.parameter('sort'),
this.parameter('page-offset'),
this.parameter('page-limit'),
...this.generateFilterParameters(model)
);
}
const result = {
operationId: `fetch-${model.name}-related-${field.name}`,
description: `Fetch the related "${field.name}" resource for "${model.name}"`,
tags: [lowerCaseFirst(model.name)],
parameters,
responses: {
'200': this.success(
field.type.array ? `${relationDecl.name}ListResponse` : `${relationDecl.name}Response`
),
'403': this.forbidden(),
'404': this.notFound(),
},
security: resourceMeta?.security ?? policies.read === true ? [] : undefined,
};
return result;
}
private makeResourceUpdate(
model: DataModel,
policies: Policies,
operationId: string,
resourceMeta: { security?: object } | undefined
) {
return {
operationId,
description: `Update a "${model.name}" resource`,
tags: [lowerCaseFirst(model.name)],
parameters: [this.parameter('id')],
requestBody: {
content: {
'application/vnd.api+json': {
schema: this.ref(`${model.name}UpdateRequest`),
},
},
},
responses: {
'200': this.success(`${model.name}Response`),
'403': this.forbidden(),
'404': this.notFound(),
'422': this.validationError(),
},
security: resourceMeta?.security ?? policies.update === true ? [] : undefined,
};
}
private makeResourceDelete(model: DataModel, policies: Policies, resourceMeta: { security?: object } | undefined) {
return {
operationId: `delete-${model.name}`,
description: `Delete a "${model.name}" resource`,
tags: [lowerCaseFirst(model.name)],
parameters: [this.parameter('id')],
responses: {
'200': this.success(),
'403': this.forbidden(),
'404': this.notFound(),
},
security: resourceMeta?.security ?? policies.delete === true ? [] : undefined,
};
}
private makeRelationshipFetch(
model: DataModel,
field: DataModelField,
policies: Policies,
resourceMeta: { security?: object } | undefined
) {
const parameters: OAPI.OperationObject['parameters'] = [this.parameter('id')];
if (field.type.array) {
parameters.push(
this.parameter('sort'),
this.parameter('page-offset'),
this.parameter('page-limit'),
...this.generateFilterParameters(model)
);
}
return {
operationId: `fetch-${model.name}-relationship-${field.name}`,
description: `Fetch the "${field.name}" relationships for a "${model.name}"`,
tags: [lowerCaseFirst(model.name)],
parameters,
responses: {
'200': field.type.array
? this.success('_toManyRelationshipResponse')
: this.success('_toOneRelationshipResponse'),
'403': this.forbidden(),
'404': this.notFound(),
},
security: resourceMeta?.security ?? policies.read === true ? [] : undefined,
};
}
private makeRelationshipCreate(
model: DataModel,
field: DataModelField,
policies: Policies,
resourceMeta: { security?: object } | undefined
) {
return {
operationId: `create-${model.name}-relationship-${field.name}`,
description: `Create new "${field.name}" relationships for a "${model.name}"`,
tags: [lowerCaseFirst(model.name)],
parameters: [this.parameter('id')],
requestBody: {
content: {
'application/vnd.api+json': {
schema: this.ref('_toManyRelationshipRequest'),
},
},
},
responses: {
'200': this.success('_toManyRelationshipResponse'),
'403': this.forbidden(),
'404': this.notFound(),
},
security: resourceMeta?.security ?? policies.update === true ? [] : undefined,
};
}
private makeRelationshipUpdate(
model: DataModel,
field: DataModelField,
policies: Policies,
operationId: string,
resourceMeta: { security?: object } | undefined
) {
return {
operationId,
description: `Update "${field.name}" ${pluralize('relationship', field.type.array ? 2 : 1)} for a "${
model.name
}"`,
tags: [lowerCaseFirst(model.name)],
parameters: [this.parameter('id')],
requestBody: {
content: {
'application/vnd.api+json': {
schema: field.type.array
? this.ref('_toManyRelationshipRequest')
: this.ref('_toOneRelationshipRequest'),
},
},
},
responses: {
'200': field.type.array
? this.success('_toManyRelationshipResponse')
: this.success('_toOneRelationshipResponse'),
'403': this.forbidden(),
'404': this.notFound(),
},
security: resourceMeta?.security ?? policies.update === true ? [] : undefined,
};
}
private generateFilterParameters(model: DataModel) {
const result: OAPI.ParameterObject[] = [];
const hasMultipleIds = model.fields.filter((f) => isIdField(f)).length > 1;
for (const field of model.fields) {
if (isForeignKeyField(field)) {
// no filtering with foreign keys because one can filter
// directly on the relationship
continue;
}
// For multiple ids, make each id field filterable like a regular field
if (isIdField(field) && !hasMultipleIds) {
// id filter
result.push(this.makeFilterParameter(field, 'id', 'Id filter'));
continue;
}
// equality filter
result.push(this.makeFilterParameter(field, '', 'Equality filter', field.type.array));
if (isRelationshipField(field)) {
// TODO: how to express nested filters?
continue;
}
if (field.type.array) {
// collection filters
result.push(this.makeFilterParameter(field, '$has', 'Collection contains filter'));
result.push(this.makeFilterParameter(field, '$hasEvery', 'Collection contains-all filter', true));
result.push(this.makeFilterParameter(field, '$hasSome', 'Collection contains-any filter', true));
result.push(
this.makeFilterParameter(field, '$isEmpty', 'Collection is empty filter', false, {
type: 'boolean',
})
);
} else {
if (field.type.type && ['Int', 'BigInt', 'Float', 'Decimal', 'DateTime'].includes(field.type.type)) {
// comparison filters
result.push(this.makeFilterParameter(field, '$lt', 'Less-than filter'));
result.push(this.makeFilterParameter(field, '$lte', 'Less-than or equal filter'));
result.push(this.makeFilterParameter(field, '$gt', 'Greater-than filter'));
result.push(this.makeFilterParameter(field, '$gte', 'Greater-than or equal filter'));
}
if (field.type.type === 'String') {
result.push(this.makeFilterParameter(field, '$contains', 'String contains filter'));
result.push(
this.makeFilterParameter(field, '$icontains', 'String case-insensitive contains filter')
);
result.push(this.makeFilterParameter(field, '$search', 'String full-text search filter'));
result.push(this.makeFilterParameter(field, '$startsWith', 'String startsWith filter'));
result.push(this.makeFilterParameter(field, '$endsWith', 'String endsWith filter'));
}
}
}
return result;
}
private makeFilterParameter(
field: DataModelField,
name: string,
description: string,
array = false,
schemaOverride?: OAPI.SchemaObject
) {
let schema: OAPI.SchemaObject | OAPI.ReferenceObject;
if (schemaOverride) {
schema = schemaOverride;
} else {
const fieldDecl = field.type.reference?.ref;
if (isEnum(fieldDecl)) {
schema = this.ref(fieldDecl.name);
} else if (isDataModel(fieldDecl)) {
schema = { type: 'string' };
} else if (isTypeDef(fieldDecl) || field.type.type === 'Json') {
schema = { type: 'string', format: 'json' };
} else {
invariant(field.type.type);
schema = this.fieldTypeToOpenAPISchema(field.type);
}
}
schema = this.wrapArray(schema, array);
return {
name: name === 'id' ? 'filter[id]' : `filter[${field.name}${name}]`,
required: false,
description: name === 'id' ? description : `${description} for "${field.name}"`,
in: 'query',
style: 'form',
explode: false,
schema,
} as OAPI.ParameterObject;
}
private generateComponents() {
const schemas: Record<string, OAPI.SchemaObject> = {};
const parameters: Record<string, OAPI.ParameterObject> = {};
const components: OAPI.ComponentsObject = {
schemas,
parameters,
};
for (const [name, value] of Object.entries(this.generateSharedComponents())) {
schemas[name] = value;
}
for (const [name, value] of Object.entries(this.generateParameters())) {
parameters[name] = value;
}
for (const _enum of this.model.declarations.filter((d): d is Enum => isEnum(d))) {
schemas[_enum.name] = this.generateEnumComponent(_enum);
}
// data models
for (const model of getDataModels(this.model)) {
for (const [name, value] of Object.entries(this.generateDataModelComponents(model))) {
schemas[name] = value;
}
}
// type defs
for (const typeDef of this.model.declarations.filter(isTypeDef)) {
schemas[typeDef.name] = this.generateTypeDefComponent(typeDef);
}
return components;
}
private generateSharedComponents(): Record<string, OAPI.SchemaObject> {
return {
_jsonapi: {
type: 'object',
description: 'An object describing the server’s implementation',
required: ['version'],
properties: {
version: { type: 'string' },
},
},
_meta: {
type: 'object',
description: 'Meta information about the request or response',
properties: {
serialization: {
description: 'Superjson serialization metadata',
},
},
additionalProperties: true,
},
_resourceIdentifier: {
type: 'object',
description: 'Identifier for a resource',
required: ['type', 'id'],
properties: {
type: { type: 'string', description: 'Resource type' },
id: { type: 'string', description: 'Resource id' },
},
},
_resource: this.allOf(this.ref('_resourceIdentifier'), {
type: 'object',
description: 'A resource with attributes and relationships',
properties: {
attributes: { type: 'object', description: 'Resource attributes' },
relationships: { type: 'object', description: 'Resource relationships' },
},
}),
_links: {
type: 'object',
required: ['self'],
description: 'Links related to the resource',
properties: { self: { type: 'string', description: 'Link for refetching the curent results' } },
},
_pagination: {
type: 'object',
description: 'Pagination information',
required: ['first', 'last', 'prev', 'next'],
properties: {
first: this.wrapNullable({ type: 'string', description: 'Link to the first page' }, true),
last: this.wrapNullable({ type: 'string', description: 'Link to the last page' }, true),
prev: this.wrapNullable({ type: 'string', description: 'Link to the previous page' }, true),
next: this.wrapNullable({ type: 'string', description: 'Link to the next page' }, true),
},
},
_errors: {
type: 'array',
description: 'An array of error objects',
items: {
type: 'object',
required: ['status', 'code'],
properties: {
status: { type: 'string', description: 'HTTP status' },
code: { type: 'string', description: 'Error code' },
prismaCode: {
type: 'string',
description: 'Prisma error code if the error is thrown by Prisma',
},
title: { type: 'string', description: 'Error title' },
detail: { type: 'string', description: 'Error detail' },
reason: {
type: 'string',
description: 'Detailed error reason',
},
zodErrors: {
type: 'object',
additionalProperties: true,
description: 'Zod validation errors if the error is due to data validation failure',
},
},
},
},
_errorResponse: {
type: 'object',
required: ['errors'],
description: 'An error response',
properties: {
jsonapi: this.ref('_jsonapi'),
errors: this.ref('_errors'),
},
},
_relationLinks: {
type: 'object',
required: ['self', 'related'],
description: 'Links related to a relationship',
properties: {
self: { type: 'string', description: 'Link for fetching this relationship' },
related: {
type: 'string',
description: 'Link for fetching the resource represented by this relationship',
},
},
},
_toOneRelationship: {
type: 'object',
description: 'A to-one relationship',
properties: {
data: this.wrapNullable(this.ref('_resourceIdentifier'), true),
},
},
_toOneRelationshipWithLinks: {
type: 'object',
required: ['links', 'data'],
description: 'A to-one relationship with links',
properties: {
links: this.ref('_relationLinks'),
data: this.wrapNullable(this.ref('_resourceIdentifier'), true),
},
},
_toManyRelationship: {
type: 'object',
required: ['data'],
description: 'A to-many relationship',
properties: {
data: this.array(this.ref('_resourceIdentifier')),
},
},
_toManyRelationshipWithLinks: {
type: 'object',
required: ['links', 'data'],
description: 'A to-many relationship with links',
properties: {
links: this.ref('_pagedRelationLinks'),
data: this.array(this.ref('_resourceIdentifier')),
},
},
_pagedRelationLinks: {
description: 'Relationship links with pagination information',
...this.allOf(this.ref('_pagination'), this.ref('_relationLinks')),
},
_toManyRelationshipRequest: {
type: 'object',
required: ['data'],
description: 'Input for manipulating a to-many relationship',
properties: {
data: {
type: 'array',
items: this.ref('_resourceIdentifier'),
},
},
},
_toOneRelationshipRequest: {
description: 'Input for manipulating a to-one relationship',
...this.wrapNullable(
{
type: 'object',
required: ['data'],
properties: {
data: this.ref('_resourceIdentifier'),
},
},
true
),
},
_toManyRelationshipResponse: {
description: 'Response for a to-many relationship',
...this.allOf(this.ref('_toManyRelationshipWithLinks'), {
type: 'object',
properties: {
jsonapi: this.ref('_jsonapi'),
},
}),
},
_toOneRelationshipResponse: {
description: 'Response for a to-one relationship',
...this.allOf(this.ref('_toOneRelationshipWithLinks'), {
type: 'object',
properties: {
jsonapi: this.ref('_jsonapi'),
},
}),
},
};
}
private generateParameters(): Record<string, OAPI.ParameterObject> {
return {
id: {
name: 'id',
in: 'path',
description: 'The resource id',
required: true,
schema: { type: 'string' },
},
include: {
name: 'include',
in: 'query',
description: 'Relationships to include',
required: false,
style: 'form',
schema: { type: 'string' },
},
sort: {
name: 'sort',
in: 'query',
description: 'Fields to sort by',
required: false,
style: 'form',
schema: { type: 'string' },
},
'page-offset': {
name: 'page[offset]',
in: 'query',
description: 'Offset for pagination',
required: false,
style: 'form',
schema: { type: 'integer' },
},
'page-limit': {
name: 'page[limit]',
in: 'query',
description: 'Limit for pagination',
required: false,
style: 'form',
schema: { type: 'integer' },
},
};
}
private generateEnumComponent(_enum: Enum) {
const schema: OAPI.SchemaObject = {
type: 'string',
description: `The "${_enum.name}" Enum`,
enum: _enum.fields.map((f) => f.name),
};
return schema;
}
private generateTypeDefComponent(typeDef: TypeDef) {
const schema: OAPI.SchemaObject = {
type: 'object',
description: `The "${typeDef.name}" TypeDef`,
properties: typeDef.fields.reduce((acc, field) => {
acc[field.name] = this.generateField(field);
return acc;
}, {} as Record<string, OAPI.SchemaObject>),
};
return schema;
}
private generateDataModelComponents(model: DataModel) {
const result: Record<string, OAPI.SchemaObject> = {};
result[`${model.name}`] = this.generateModelEntity(model, 'read');
result[`${model.name}CreateRequest`] = {
type: 'object',
description: `Input for creating a "${model.name}"`,
required: ['data'],
properties: {
data: this.generateModelEntity(model, 'create'),
meta: this.ref('_meta'),
},
};
result[`${model.name}UpdateRequest`] = {
type: 'object',
description: `Input for updating a "${model.name}"`,
required: ['data'],
properties: { data: this.generateModelEntity(model, 'update'), meta: this.ref('_meta') },
};
const relationships: Record<string, OAPI.ReferenceObject> = {};
for (const field of model.fields) {
if (isRelationshipField(field)) {
if (field.type.array) {
relationships[field.name] = this.ref('_toManyRelationship');
} else {
relationships[field.name] = this.ref('_toOneRelationship');
}
}
}
result[`${model.name}Response`] = {
type: 'object',
description: `Response for a "${model.name}"`,
required: ['data'],
properties: {
jsonapi: this.ref('_jsonapi'),
data: this.allOf(this.ref(`${model.name}`), {
type: 'object',
properties: { relationships: { type: 'object', properties: relationships } },
}),
meta: this.ref('_meta'),
included: {
type: 'array',
items: this.ref('_resource'),
},
links: this.ref('_links'),
},
};
result[`${model.name}ListResponse`] = {
type: 'object',
description: `Response for a list of "${model.name}"`,
required: ['data', 'links'],
properties: {
jsonapi: this.ref('_jsonapi'),
data: this.array(
this.allOf(this.ref(`${model.name}`), {
type: 'object',
properties: { relationships: { type: 'object', properties: relationships } },
})
),
meta: this.ref('_meta'),
included: {
type: 'array',
items: this.ref('_resource'),
},
links: this.allOf(this.ref('_links'), this.ref('_pagination')),
},
};
return result;
}
private generateModelEntity(model: DataModel, mode: 'read' | 'create' | 'update'): OAPI.SchemaObject {
const idFields = model.fields.filter((f) => isIdField(f));
// For compound ids each component is also exposed as a separate fields.
const fields = idFields.length > 1 ? model.fields : model.fields.filter((f) => !isIdField(f));
const attributes: Record<string, OAPI.SchemaObject> = {};
const relationships: Record<string, OAPI.ReferenceObject | OAPI.SchemaObject> = {};
const required: string[] = [];
for (const field of fields) {
if (isForeignKeyField(field) && mode !== 'read') {
// foreign keys are not exposed as attributes
continue;
}
if (isRelationshipField(field)) {
let relType: string;
if (mode === 'create' || mode === 'update') {
relType = field.type.array ? '_toManyRelationship' : '_toOneRelationship';
} else {
relType = field.type.array ? '_toManyRelationshipWithLinks' : '_toOneRelationshipWithLinks';
}
relationships[field.name] = this.wrapNullable(this.ref(relType), field.type.optional);
} else {
attributes[field.name] = this.generateField(field);
if (
mode === 'create' &&
!field.type.optional &&
!hasAttribute(field, '@default') &&
// collection relation fields are implicitly optional
!(isDataModel(field.$resolvedType?.decl) && field.type.array)
) {
required.push(field.name);
} else if (mode === 'read') {
// Until we support sparse fieldsets, all fields are required for read operations
required.push(field.name);
}
}
}
const toplevelRequired = ['type', 'attributes'];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let properties: any = {
type: { type: 'string' },
attributes: {
type: 'object',
required: required.length > 0 ? required : undefined,
properties: attributes,
},
};
let idFieldSchema: OAPI.SchemaObject = { type: 'string' };
if (idFields.length === 1) {
// FIXME: JSON:API actually requires id field to be a string,
// but currently the RESTAPIHandler returns the original data
// type as declared in the ZModel schema.
idFieldSchema = this.fieldTypeToOpenAPISchema(idFields[0].type);
}
if (mode === 'create') {
// 'id' is required if there's no default value
const idFields = model.fields.filter((f) => isIdField(f));
if (idFields.length === 1 && !hasAttribute(idFields[0], '@default')) {
properties = { id: idFieldSchema, ...properties };
toplevelRequired.unshift('id');
}
} else {
// 'id' always required for read and update
properties = { id: idFieldSchema, ...properties };
toplevelRequired.unshift('id');
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const result: any = {
type: 'object',
description: `The "${model.name}" model`,
required: toplevelRequired,
properties,
} satisfies OAPI.SchemaObject;
if (Object.keys(relationships).length > 0) {
result.properties.relationships = {
type: 'object',
properties: relationships,
};
}
return result;
}
private generateField(field: DataModelField | TypeDefField) {
return this.wrapArray(
this.wrapNullable(this.fieldTypeToOpenAPISchema(field.type), field.type.optional),
field.type.array
);
}
private fieldTypeToOpenAPISchema(
type: DataModelFieldType | TypeDefFieldType
): OAPI.ReferenceObject | OAPI.SchemaObject {
return match(type.type)
.with('String', () => ({ type: 'string' }))
.with(P.union('Int', 'BigInt'), () => ({ type: 'integer' }))
.with('Float', () => ({ type: 'number' }))
.with('Decimal', () => this.oneOf({ type: 'number' }, { type: 'string' }))
.with('Boolean', () => ({ type: 'boolean' }))
.with('DateTime', () => ({ type: 'string', format: 'date-time' }))
.with('Bytes', () => ({ type: 'string', format: 'byte', description: 'Base64 encoded byte array' }))
.with('Json', () => ({}))
.otherwise((t) => {
const fieldDecl = type.reference?.ref;
invariant(fieldDecl, `Type ${t} is not a model reference`);