-
Notifications
You must be signed in to change notification settings - Fork 102
/
Copy pathzod-openapi.spec.ts
1120 lines (1059 loc) · 31.4 KB
/
zod-openapi.spec.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
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
import { SchemaObject } from 'openapi3-ts/oas31';
import validator from 'validator';
import { z } from 'zod';
import { generateSchema, extendApi } from './zod-openapi';
describe('zodOpenapi', () => {
/**
* Primitives
*/
it('should support basic primitives', () => {
const zodSchema = extendApi(
z.object({
aString: z.string().describe('A test string').optional(),
aNumber: z.number().optional(),
aBigInt: z.bigint(),
aBoolean: z.boolean(),
aDate: z.date(),
}),
{
description: `Primitives also testing overwriting of "required"`,
required: ['aNumber'], // All schema settings "merge"
}
);
const apiSchema = generateSchema(zodSchema);
expect(apiSchema).toEqual({
type: ['object'],
properties: {
aString: { description: 'A test string', type: ['string'] },
aNumber: { type: ['number'] },
aBigInt: { type: ['integer'], format: 'int64' },
aBoolean: { type: ['boolean'] },
aDate: { type: ['string'], format: 'date-time' },
},
required: ['aBigInt', 'aBoolean', 'aDate', 'aNumber'],
description: 'Primitives also testing overwriting of "required"',
});
});
it('should support basic primitives for OpenAPI v3.0', () => {
const zodSchema = extendApi(
z.object({
aString: z.string().describe('A test string').optional(),
aNumber: z.number().optional(),
aBigInt: z.bigint(),
aBoolean: z.boolean(),
aDate: z.date(),
}),
{
description: `Primitives also testing overwriting of "required"`,
required: ['aNumber'], // All schema settings "merge"
}
);
const apiSchema = generateSchema(zodSchema, false, '3.0');
expect(apiSchema).toEqual({
type: 'object',
properties: {
aString: { description: 'A test string', type: 'string' },
aNumber: { type: 'number' },
aBigInt: { type: 'integer', format: 'int64' },
aBoolean: { type: 'boolean' },
aDate: { type: 'string', format: 'date-time' },
},
required: ['aBigInt', 'aBoolean', 'aDate', 'aNumber'],
description: 'Primitives also testing overwriting of "required"',
});
});
it('should support empty types', () => {
const zodSchema = extendApi(
z.object({
aUndefined: z.undefined(),
aNull: z.null(),
aVoid: z.void(),
}),
{
description: `Empty types in a schema`,
}
);
const apiSchema = generateSchema(zodSchema);
expect(apiSchema).toEqual({
type: ['object'],
properties: {
aUndefined: {},
aNull: { type: ['string', 'null'], enum: ['null'] },
aVoid: {},
},
required: ['aNull'],
description: 'Empty types in a schema',
});
});
it('It should support proper transform input/output', () => {
const zodTransform = extendApi(
z.string().transform((val) => val.length),
{ description: 'Will take in a string, returning the length' }
);
const schemaIn = generateSchema(zodTransform);
expect(schemaIn.type).toEqual(['string']);
const schemaOut = generateSchema(zodTransform, true);
expect(schemaOut.type).toEqual(['number']);
});
it('should support catch-all types', () => {
const zodSchema = extendApi(
z.object({
aAny: z.any(),
aUnknown: z.unknown(),
}),
{
description: `Empty types don't belong in schema`,
}
);
const apiSchema = generateSchema(zodSchema);
expect(apiSchema.properties).toBeDefined();
});
it('should support never type', () => {
const zodSchema = extendApi(
z.object({
aNever: z.never(),
}),
{
description: `Never values! Can not use them!`,
}
);
const apiSchema = generateSchema(zodSchema);
expect(apiSchema.properties).toBeDefined();
expect((apiSchema.properties?.aNever as SchemaObject).readOnly).toEqual(
true
);
})
it('should support branded types', () => {
const zodSchema = extendApi(
z.object({
aBrandedString: z.string().describe('A branded test string').brand('BrandedString').optional(),
aBrandedNumber: z.number().brand('BrandedNumber').optional(),
aBrandedBigInt: z.bigint().brand('BrandedBigInt'),
aBrandedBoolean: z.boolean().brand('BrandedBoolean'),
aBrandedDate: z.date().brand('BrandedDate'),
}),
{
description: `Branded primitives`
}
);
const apiSchema = generateSchema(zodSchema);
expect(apiSchema).toEqual({
type: ['object'],
properties: {
aBrandedString: { description: 'A branded test string', type: ['string'] },
aBrandedNumber: { type: ['number'] },
aBrandedBigInt: { type: ['integer'], format: 'int64' },
aBrandedBoolean: { type: ['boolean'] },
aBrandedDate: { type: ['string'], format: 'date-time' },
},
required: ['aBrandedBigInt', 'aBrandedBoolean', 'aBrandedDate'],
description: 'Branded primitives',
});
});
it('should support string and string constraints', () => {
const zodSchema = extendApi(
z
.object({
aStringMax: z.string().max(5),
aStringMin: z.string().min(3),
aStringLength: z.string().length(10),
aStringEmail: z.string().email(),
aStringUrl: z.string().url(),
aStringUUID: z.string().uuid(),
aStringDatetime: z.string().datetime(),
aStringCUID: z.string().cuid(),
aStringRegex: z.string().regex(/^[a-zA-Z]+$/),
aStringNonEmpty: z.string().nonempty(),
})
.partial(),
{
description: `This is totally unlike String Theory`,
}
);
const apiSchema = generateSchema(zodSchema);
expect(apiSchema).toEqual({
type: ['object'],
properties: {
aStringMax: { type: ['string'], maxLength: 5 },
aStringMin: { type: ['string'], minLength: 3 },
aStringLength: { maxLength: 10, minLength: 10, type: ['string'] },
aStringEmail: { type: ['string'], format: 'email' },
aStringUrl: { type: ['string'], format: 'uri' },
aStringUUID: { type: ['string'], format: 'uuid' },
aStringCUID: { type: ['string'], format: 'cuid' },
aStringDatetime: { type: ['string'], format: 'date-time' },
aStringRegex: { type: ['string'], pattern: '^[a-zA-Z]+$' },
aStringNonEmpty: { type: ['string'], minLength: 1 },
},
description: 'This is totally unlike String Theory',
});
});
it('should support numbers and number constraints', () => {
const zodSchema = extendApi(
z
.object({
aNumberMin: z.number().min(3),
aNumberMax: z.number().max(8),
aNumberInt: z.number().int(),
aNumberPositive: z.number().positive(),
aNumberNonnegative: z.number().nonnegative(),
aNumberNegative: z.number().negative(),
aNumberNonpositive: z.number().nonpositive(),
aNumberGt: z.number().gt(5),
aNumberLt: z.number().lt(5),
aNumberMultipleOf: z.number().multipleOf(2),
})
.partial(),
{
description: `Look mah, the horse can count higher than me!`,
}
);
const apiSchema = generateSchema(zodSchema);
expect(apiSchema).toEqual({
type: ['object'],
properties: {
aNumberMin: { type: ['number'], minimum: 3 },
aNumberMax: { type: ['number'], maximum: 8 },
aNumberInt: { type: ['integer'] },
aNumberPositive: { type: ['number'], exclusiveMinimum: 0 },
aNumberNonnegative: { type: ['number'], minimum: 0 },
aNumberNegative: { type: ['number'], exclusiveMaximum: 0 },
aNumberNonpositive: { type: ['number'], maximum: 0 },
aNumberGt: { type: ['number'], exclusiveMinimum: 5 },
aNumberLt: { type: ['number'], exclusiveMaximum: 5 },
aNumberMultipleOf: { type: ['number'], multipleOf: 2 },
},
description: 'Look mah, the horse can count higher than me!',
});
});
it('should support arrays and array constraints', () => {
const zodSchema = extendApi(
z
.object({
aArrayMin: z.array(z.string()).min(3),
aArrayMax: z.array(z.number()).max(8),
aArrayLength: z.array(z.boolean()).length(10),
aArrayNonempty: z.array(z.null()).nonempty(),
aArrayMinAndMax: z.array(z.number()).min(3).max(8),
})
.partial(),
{
description: 'I need arrays',
}
);
const apiSchema = generateSchema(zodSchema);
expect(apiSchema).toEqual({
type: ['object'],
properties: {
aArrayMin: { type: ['array'], minItems: 3, items: { type: ['string'] } },
aArrayMax: { type: ['array'], maxItems: 8, items: { type: ['number'] } },
aArrayLength: {
type: ['array'],
minItems: 10,
maxItems: 10,
items: { type: ['boolean'] },
},
aArrayNonempty: {
type: ['array'],
minItems: 1,
items: { type: ['string', 'null'], enum: ['null'] },
},
aArrayMinAndMax: {
type: ['array'],
minItems: 3,
maxItems: 8,
items: { type: ['number'] },
},
},
description: 'I need arrays',
});
});
describe('Regarding omitted schema definitions', () => {
it('supports schema hideDefinitions properties', () => {
const zodSchema = extendApi(
z
.object({
aArrayMin: z.array(z.string()).min(3),
aArrayMax: z.array(z.number()).max(8),
aArrayLength: z.array(z.boolean()).length(10),
})
.partial(),
{
description: 'I need arrays',
hideDefinitions: ['aArrayLength'],
}
);
const apiSchema = generateSchema(zodSchema);
expect(apiSchema).toEqual({
type: ['object'],
properties: {
aArrayMin: {
type: ['array'],
minItems: 3,
items: { type: ['string'] },
},
aArrayMax: {
type: ['array'],
maxItems: 8,
items: { type: ['number'] },
},
},
"hideDefinitions": ["aArrayLength"],
description: 'I need arrays',
});
});
it('supports hideDefinitions on nested schemas', () => {
const zodNestedSchema = extendApi(
z.strictObject({
aString: z.string(),
aNumber: z.number().optional()
}),
{
hideDefinitions: ['aNumber']
}
)
const zodSchema = extendApi(
z.object({ data: zodNestedSchema }).partial(),
{
description: 'I need arrays',
}
);
const apiSchema = generateSchema(zodSchema);
expect(apiSchema).toEqual({
"description": "I need arrays",
"properties": {
"data": {
"additionalProperties": false,
"properties": {
"aString": {
"type": ["string"],
},
},
"hideDefinitions": ["aNumber"],
"required": [
"aString",
],
"type": ["object"],
},
},
"type": ["object"],
}
);
});
});
describe('record support', () => {
describe('with a value type', () => {
it('adds the value type to additionalProperties', () => {
const zodSchema = extendApi(z.record(z.number().min(2).max(42)), {
description: 'Record this one for me.',
});
const apiSchema = generateSchema(zodSchema);
expect(apiSchema).toEqual({
type: ['object'],
additionalProperties: { type: ['number'], minimum: 2, maximum: 42 },
description: 'Record this one for me.',
});
});
});
describe('with unknown value types', () => {
it('leaves additionalProperties blank', () => {
const zodSchema = extendApi(z.record(z.unknown()), {
description: 'Record this one for me.',
});
const apiSchema = generateSchema(zodSchema);
expect(apiSchema).toEqual({
type: ['object'],
additionalProperties: {},
description: 'Record this one for me.',
});
});
});
});
it('should support schemas with a default', () => {
const zodSchema = extendApi(
z.object({
aString: z.string().default('hello'),
aStringWithConstraints: z.string().email().max(100).default('hello'),
aNumber: z.number().default(42),
aNumberWithRestrictions: z.number().min(2).max(42).default(42),
aBoolean: z.boolean().default(false),
nonDefaulted: z.string(),
}),
{
description: 'I defaulted on my debt',
}
);
const apiSchema = generateSchema(zodSchema);
expect(apiSchema).toEqual({
type: ['object'],
properties: {
aString: { type: ['string'], default: 'hello' },
aStringWithConstraints: {
type: ['string'],
format: 'email',
maxLength: 100,
default: 'hello',
},
aNumber: { type: ['number'], default: 42 },
aNumberWithRestrictions: {
type: ['number'],
minimum: 2,
maximum: 42,
default: 42,
},
aBoolean: { type: ['boolean'], default: false },
nonDefaulted: { type: ['string'] },
},
required: ['nonDefaulted'],
description: 'I defaulted on my debt',
});
});
it('should support an object schema that has a default on itself', () => {
const zodSchema = extendApi(
z
.object({
aString: z.string(),
aNumber: z.number(),
})
.default({
aString: 'hello',
aNumber: 42,
}),
{
description: 'I defaulted on my debt',
}
);
const apiSchema = generateSchema(zodSchema);
expect(apiSchema).toEqual({
type: ['object'],
properties: {
aString: { type: ['string'] },
aNumber: { type: ['number'] },
},
default: {
aString: 'hello',
aNumber: 42,
},
required: ['aString', 'aNumber'],
description: 'I defaulted on my debt',
});
});
it('should support `catchall` on an object schema', () => {
const zodSchema = extendApi(
z
.object({
aString: z.string(),
aNumber: z.number(),
})
.catchall(
z.object({
email: z.string().email(),
available: z.boolean(),
})
),
{
description: "Gotta catch 'em all!",
}
);
const apiSchema = generateSchema(zodSchema);
expect(apiSchema).toEqual({
type: ['object'],
required: ['aString', 'aNumber'],
properties: {
aString: { type: ['string'] },
aNumber: { type: ['number'] },
},
additionalProperties: {
type: ['object'],
properties: {
email: { type: ['string'], format: 'email' },
available: { type: ['boolean'] },
},
required: ['email', 'available'],
},
description: "Gotta catch 'em all!",
});
});
it('should support `passthrough` on an object schema', () => {
const zodSchema = extendApi(
z
.object({
aString: z.string(),
aNumber: z.number(),
})
.passthrough(),
{
description: "Gotta catch 'em all!",
}
);
const apiSchema = generateSchema(zodSchema);
expect(apiSchema).toEqual({
type: ['object'],
required: ['aString', 'aNumber'],
properties: {
aString: { type: ['string'] },
aNumber: { type: ['number'] },
},
additionalProperties: true,
description: "Gotta catch 'em all!",
});
});
it('should support `strict` on an object schema', () => {
const zodSchema = extendApi(
z
.object({
aString: z.string(),
aNumber: z.number(),
})
.strict(),
{
description: "Super strict",
}
);
const apiSchema = generateSchema(zodSchema);
expect(apiSchema).toEqual({
type: ['object'],
required: ['aString', 'aNumber'],
properties: {
aString: { type: ['string'] },
aNumber: { type: ['number'] },
},
additionalProperties: false,
description: "Super strict",
});
});
it('Testing large mixed schema', () => {
enum Fruits {
Apple,
Banana,
}
const MoreFruits = {
Pear: 'pear',
Plumb: 'plumb',
grapes: 3,
} as const;
const zodSchema = z.object({
name: extendApi(z.string(), { description: `User full name` }),
email: extendApi(z.string().email().min(4), {
description: 'User email',
}),
whatever: z.string().optional(),
myCollection: extendApi(
z.array(z.object({ name: z.string(), count: z.number() })),
{ maxItems: 10 }
),
timeStamp: z.string().refine(validator.isISO8601),
literals: z.object({
wordOne: z.literal('One').nullable(),
numberTwo: z.literal(2).optional(),
isThisTheEnd: z.literal(false).optional().nullable(),
}),
catchall: z
.object({
email: z.string().email(),
joined: z.date().optional(),
})
.catchall(z.object({ name: z.string(), value: z.string() })),
foodTest: extendApi(
z.object({
fishEnum: extendApi(z.enum(['Salmon', 'Tuna', 'Trout']), {
description: 'Choose your fish',
default: 'Salmon',
}),
fruitEnum: z.nativeEnum(Fruits).default(Fruits.Banana),
moreFruitsEnum: z.nativeEnum(MoreFruits),
}),
{ description: 'Have some lunch' }
),
employedPerson: extendApi(
z.intersection(
z.object({ name: z.string() }),
z.object({
role: z.enum(['manager', 'employee', 'intern', 'hopeful']),
})
),
{ description: 'Our latest addition' }
),
makeAChoice: z.union([z.literal('One'), z.literal(2)]),
chooseAPet: z.discriminatedUnion('animal', [
z.object({
animal: z.literal('dog'),
theBestQuality: z.literal('fleas'),
}),
z.object({
animal: z.literal('cat'),
theBestQuality: z.literal('stink'),
}),
]),
openChoice: extendApi(z.union([z.string(), z.string()]), {
description: 'Odd pattern here',
}),
aNullish: z.string().nullish(),
stringLengthOutput: z.string().transform((val) => val.length),
favourites: z.record(
z.object({ name: z.string(), watchCount: z.number() })
),
limit: z.number().default(200),
freeform: z
.object({
name: z.string(),
})
.passthrough(),
});
const schemaTest = generateSchema(zodSchema, true);
expect(schemaTest).toEqual({
type: ['object'],
properties: {
name: { type: ['string'], description: 'User full name' },
email: {
type: ['string'],
format: 'email',
minLength: 4,
description: 'User email',
},
whatever: { type: ['string'] },
myCollection: {
type: ['array'],
items: {
type: ['object'],
properties: { name: { type: ['string'] }, count: { type: ['number'] } },
required: ['name', 'count'],
},
maxItems: 10,
},
timeStamp: { type: ['string'] },
literals: {
type: ['object'],
properties: {
wordOne: { type: ['string', 'null'], enum: ['One'] },
numberTwo: { type: ['number'], enum: [2] },
isThisTheEnd: { type: ['boolean', 'null'], enum: [false] },
},
required: ['wordOne'],
},
catchall: {
type: ['object'],
properties: {
email: { type: ['string'], format: 'email' },
joined: { type: ['string'], format: 'date-time' },
},
required: ['email'],
additionalProperties: {
type: ['object'],
properties: {
name: { type: ['string'] },
value: { type: ['string'] },
},
required: ['name', 'value'],
},
},
foodTest: {
type: ['object'],
properties: {
fishEnum: {
type: ['string'],
enum: ['Salmon', 'Tuna', 'Trout'],
description: 'Choose your fish',
default: 'Salmon',
},
fruitEnum: {
type: ['string'],
enum: ['Apple', 'Banana', 0, 1],
default: 1,
},
moreFruitsEnum: { type: ['string'], enum: ['pear', 'plumb', 3] },
},
required: ['fishEnum', 'moreFruitsEnum'],
description: 'Have some lunch',
},
employedPerson: {
allOf: [
{
type: ['object'],
properties: { name: { type: ['string'] } },
required: ['name'],
},
{
type: ['object'],
properties: {
role: {
type: ['string'],
enum: ['manager', 'employee', 'intern', 'hopeful'],
},
},
required: ['role'],
},
],
description: 'Our latest addition',
},
makeAChoice: {
oneOf: [
{ type: ['string'], enum: ['One'] },
{ type: ['number'], enum: [2] },
],
},
chooseAPet: {
discriminator: {
propertyName: 'animal',
},
oneOf: [
{
properties: {
animal: {
enum: ['dog'],
type: ['string'],
},
theBestQuality: {
enum: ['fleas'],
type: ['string'],
},
},
required: ['animal', 'theBestQuality'],
type: ['object'],
},
{
properties: {
animal: {
enum: ['cat'],
type: ['string'],
},
theBestQuality: {
enum: ['stink'],
type: ['string'],
},
},
required: ['animal', 'theBestQuality'],
type: ['object'],
},
],
},
openChoice: {
oneOf: [{ type: ['string'] }, { type: ['string'] }],
description: 'Odd pattern here',
},
aNullish: { type: ['string', 'null'] },
stringLengthOutput: { type: ['number'] },
favourites: {
type: ['object'],
additionalProperties: {
type: ['object'],
properties: {
name: { type: ['string'] },
watchCount: { type: ['number'] },
},
required: ['name', 'watchCount'],
},
},
limit: { type: ['number'], default: 200 },
freeform: {
type: ['object'],
properties: {
name: { type: ['string'] },
},
additionalProperties: true,
required: ['name'],
},
},
required: [
'name',
'email',
'myCollection',
'timeStamp',
'literals',
'catchall',
'foodTest',
'employedPerson',
'makeAChoice',
'chooseAPet',
'openChoice',
'stringLengthOutput',
'favourites',
'freeform',
],
});
// const builder = OpenApiBuilder.create();
// builder.addSchema('Users', schemaTest);
// builder;
});
it('Experimentation', () => {
const UserZ = z.object({
uid: extendApi(z.string().nonempty(), {
description: 'A firebase generated UUID',
format: 'firebase-uuid',
}),
theme: extendApi(z.enum([`light`, `dark`]), {
description: 'Defaults to light theme',
default: 'light',
}),
email: z.string().email().optional(),
phoneNumber: z.string().min(10).optional(),
});
const openApiSchema: SchemaObject = generateSchema(UserZ);
expect(openApiSchema.properties).toBeDefined();
});
it('Take any Zod schema and convert it to an OpenAPI JSON object', () => {
const aZodSchema = z.object({
uid: z.string().nonempty(),
firstName: z.string().min(2),
lastName: z.string().optional(),
email: z.string().email(),
phoneNumber: z.string().min(10).optional(),
});
const myOpenApiSchema = generateSchema(aZodSchema);
expect(myOpenApiSchema).toEqual({
type: ['object'],
properties: {
uid: { type: ['string'], minLength: 1 },
firstName: { type: ['string'], minLength: 2 },
lastName: { type: ['string'] },
email: { type: ['string'], format: 'email' },
phoneNumber: { type: ['string'], minLength: 10 },
},
required: ['uid', 'firstName', 'email'],
});
});
it('Extend a Zod schema with additional OpenAPI schema via a function wrapper', () => {
const aZodExtendedSchema = extendApi(
z.object({
uid: extendApi(z.string().nonempty(), {
title: 'Unique ID',
description: 'A UUID generated by the server',
}),
firstName: z.string().min(2),
lastName: z.string().optional(),
email: z.string().email(),
phoneNumber: extendApi(z.string().min(10), {
description: 'US Phone numbers only',
examples: ['555-555-5555'],
}),
}),
{
title: 'User',
description: 'A user schema',
}
);
const myOpenApiSchema = generateSchema(aZodExtendedSchema);
expect(myOpenApiSchema).toEqual({
type: ['object'],
properties: {
uid: {
type: ['string'],
minLength: 1,
title: 'Unique ID',
description: 'A UUID generated by the server',
},
firstName: { type: ['string'], minLength: 2 },
lastName: { type: ['string'] },
email: { type: ['string'], format: 'email' },
phoneNumber: {
type: ['string'],
minLength: 10,
description: 'US Phone numbers only',
examples: ['555-555-5555'],
},
},
required: ['uid', 'firstName', 'email', 'phoneNumber'],
title: 'User',
description: 'A user schema',
});
});
it('merges openapi metadata when extendApi is used more than one', () => {
const timestampSchema = extendApi(z.string(), {
format: 'date-time',
description: 'A timestamp.',
});
const newDescription = 'A more specific timestamp.';
const overriddenSchema = extendApi(timestampSchema, {
description: newDescription,
});
const openapiSchema = generateSchema(overriddenSchema);
expect(openapiSchema).toMatchObject({
type: ['string'],
format: 'date-time',
description: newDescription,
});
});
it('Can cast a string to binary type', () => {
const binarySchema = extendApi(z.string(), {
format: 'binary',
});
const openapiSchema = generateSchema(binarySchema);
expect(openapiSchema).toMatchObject({
type: ['string'],
format: 'binary',
});
});
it('can summarize unions of zod literals as an enum', () => {
expect(generateSchema(z.union([z.literal('h'), z.literal('i')]))).toEqual({
type: ['string'],
enum: ['h', 'i']
});
expect(generateSchema(z.union([z.literal(3), z.literal(4)]))).toEqual({
type: ['number'],
enum: [3, 4]
});
// should this just remove the enum? true | false is exhaustive...
expect(generateSchema(z.union([z.literal(true), z.literal(false)]))).toEqual({
type: ['boolean'],
enum: [true, false]
});
expect(generateSchema(z.union([z.literal(5), z.literal('i')]))).toEqual({
oneOf: [
{
type: ['number'],
enum: [5]
},
{
type: ['string'],
enum: ['i']
}
]
});
})
it('should work with ZodPipeline', () => {
expect(
generateSchema(
z
.string()
.regex(/^\d+$/)
.transform(Number)
.pipe(z.number().min(0).max(10))
)
).toEqual({
type: ['string'],
pattern: '^\\d+$',
} satisfies SchemaObject);
expect(
generateSchema(
z
.string()
.regex(/^\d+$/)
.transform(Number)
.pipe(z.number().min(0).max(10)),
true
)
).toEqual({
type: ['number'],
minimum: 0,
maximum: 10,
} satisfies SchemaObject);
});
it('should work with ZodPipeline and additional extendApi', () => {
expect(
generateSchema(
extendApi(
z
.string()