-
-
Notifications
You must be signed in to change notification settings - Fork 144
Expand file tree
/
Copy pathopenapi-rpc.test.ts
More file actions
663 lines (543 loc) · 20.1 KB
/
openapi-rpc.test.ts
File metadata and controls
663 lines (543 loc) · 20.1 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
/* eslint-disable @typescript-eslint/no-explicit-any */
/// <reference types="@types/jest" />
import OpenAPIParser from '@readme/openapi-parser';
import { getLiteral, getObjectLiteral } from '@zenstackhq/sdk';
import { Model, Plugin, isPlugin } from '@zenstackhq/sdk/ast';
import { loadSchema, loadZModelAndDmmf, normalizePath } from '@zenstackhq/testtools';
import fs from 'fs';
import path from 'path';
import * as tmp from 'tmp';
import YAML from 'yaml';
import generate from '../src';
tmp.setGracefulCleanup();
describe('Open API Plugin RPC Tests', () => {
it('run plugin', async () => {
for (const specVersion of ['3.0.0', '3.1.0']) {
for (const omitInputDetails of [true, false]) {
const { projectDir } = await loadSchema(
`
plugin openapi {
provider = '${normalizePath(path.resolve(__dirname, '../dist'))}'
specVersion = '${specVersion}'
omitInputDetails = ${omitInputDetails}
output = '$projectRoot/openapi.yaml'
}
enum role {
USER
ADMIN
}
model User {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
email String @unique
role role @default(USER)
posts post_Item[]
profile Profile?
@@openapi.meta({
findMany: {
description: 'Find users matching the given conditions'
},
delete: {
method: 'put',
path: 'dodelete',
description: 'Delete a unique user',
summary: 'Delete a user yeah yeah',
tags: ['delete', 'user'],
deprecated: true
},
})
}
model Profile {
id String @id @default(cuid())
image String?
user User @relation(fields: [userId], references: [id])
userId String @unique
}
model post_Item {
id String @id
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
title String
author User? @relation(fields: [authorId], references: [id])
authorId String?
published Boolean @default(false)
viewCount Int @default(0)
notes String?
@@openapi.meta({
tagDescription: 'Post-related operations',
findMany: {
ignore: true
}
})
}
model Foo {
id String @id
@@openapi.ignore
}
model Bar {
id String @id
@@ignore
}
`,
{ provider: 'postgresql', pushDb: false }
);
console.log(
`OpenAPI specification generated for ${specVersion}${
omitInputDetails ? ' - omit' : ''
}: ${projectDir}/openapi.yaml`
);
const parsed = YAML.parse(fs.readFileSync(path.join(projectDir, 'openapi.yaml'), 'utf-8'));
expect(parsed.openapi).toBe(specVersion);
const baseline = YAML.parse(
fs.readFileSync(
`${__dirname}/baseline/rpc-${specVersion}${omitInputDetails ? '-omit' : ''}.baseline.yaml`,
'utf-8'
)
);
expect(parsed).toMatchObject(baseline);
const api = await OpenAPIParser.validate(path.join(projectDir, 'openapi.yaml'));
expect(api.tags).toEqual(
expect.arrayContaining([
expect.objectContaining({ name: 'user', description: 'User operations' }),
expect.objectContaining({ name: 'post_Item', description: 'Post-related operations' }),
])
);
expect(api.paths?.['/user/findMany']?.['get']?.description).toBe(
'Find users matching the given conditions'
);
const del = api.paths?.['/user/dodelete']?.['put'];
expect(del?.description).toBe('Delete a unique user');
expect(del?.summary).toBe('Delete a user yeah yeah');
expect(del?.tags).toEqual(expect.arrayContaining(['delete', 'user']));
expect(del?.deprecated).toBe(true);
expect(api.paths?.['/post/findMany']).toBeUndefined();
expect(api.paths?.['/foo/findMany']).toBeUndefined();
expect(api.paths?.['/bar/findMany']).toBeUndefined();
}
}
});
it('options', async () => {
const { model, dmmf, modelFile } = await loadZModelAndDmmf(`
plugin openapi {
provider = '${normalizePath(path.resolve(__dirname, '../dist'))}'
specVersion = '3.0.0'
title = 'My Awesome API'
version = '1.0.0'
description = 'awesome api'
prefix = '/myapi'
}
model User {
id String @id
}
`);
const { name: output } = tmp.fileSync({ postfix: '.yaml' });
const options = buildOptions(model, modelFile, output);
await generate(model, options, dmmf);
console.log('OpenAPI specification generated:', output);
const parsed = YAML.parse(fs.readFileSync(output, 'utf-8'));
expect(parsed.openapi).toBe('3.0.0');
const api = await OpenAPIParser.validate(output);
expect(api.info).toEqual(
expect.objectContaining({
title: 'My Awesome API',
version: '1.0.0',
description: 'awesome api',
})
);
expect(api.paths?.['/myapi/user/findMany']).toBeTruthy();
});
it('security schemes valid', async () => {
const { model, dmmf, modelFile } = await loadZModelAndDmmf(`
plugin openapi {
provider = '${normalizePath(path.resolve(__dirname, '../dist'))}'
securitySchemes = {
myBasic: { type: 'http', scheme: 'basic' },
myBearer: { type: 'http', scheme: 'bearer', bearerFormat: 'JWT' },
myApiKey: { type: 'apiKey', in: 'header', name: 'X-API-KEY' }
}
}
model User {
id String @id
}
`);
const { name: output } = tmp.fileSync({ postfix: '.yaml' });
const options = buildOptions(model, modelFile, output);
await generate(model, options, dmmf);
console.log('OpenAPI specification generated:', output);
await OpenAPIParser.validate(output);
const parsed = YAML.parse(fs.readFileSync(output, 'utf-8'));
expect(parsed.components.securitySchemes).toEqual(
expect.objectContaining({
myBasic: { type: 'http', scheme: 'basic' },
myBearer: { type: 'http', scheme: 'bearer', bearerFormat: 'JWT' },
myApiKey: { type: 'apiKey', in: 'header', name: 'X-API-KEY' },
})
);
expect(parsed.security).toEqual(expect.arrayContaining([{ myBasic: [] }, { myBearer: [] }]));
});
it('security schemes invalid', async () => {
const { model, dmmf, modelFile } = await loadZModelAndDmmf(`
plugin openapi {
provider = '${normalizePath(path.resolve(__dirname, '../dist'))}'
securitySchemes = {
myBasic: { type: 'invalid', scheme: 'basic' }
}
}
model User {
id String @id
}
`);
const { name: output } = tmp.fileSync({ postfix: '.yaml' });
const options = buildOptions(model, modelFile, output);
await expect(generate(model, options, dmmf)).rejects.toEqual(
expect.objectContaining({ message: expect.stringContaining('"securitySchemes" option is invalid') })
);
});
it('security model level override', async () => {
const { model, dmmf, modelFile } = await loadZModelAndDmmf(`
plugin openapi {
provider = '${normalizePath(path.resolve(__dirname, '../dist'))}'
securitySchemes = {
myBasic: { type: 'http', scheme: 'basic' }
}
}
model User {
id String @id
@@openapi.meta({
security: []
})
}
`);
const { name: output } = tmp.fileSync({ postfix: '.yaml' });
const options = buildOptions(model, modelFile, output);
await generate(model, options, dmmf);
console.log('OpenAPI specification generated:', output);
const api = await OpenAPIParser.validate(output);
expect(api.paths?.['/user/findMany']?.['get']?.security).toHaveLength(0);
});
it('security operation level override', async () => {
const { model, dmmf, modelFile } = await loadZModelAndDmmf(`
plugin openapi {
provider = '${normalizePath(path.resolve(__dirname, '../dist'))}'
securitySchemes = {
myBasic: { type: 'http', scheme: 'basic' }
}
}
model User {
id String @id
@@allow('read', true)
@@openapi.meta({
security: [],
findMany: {
security: [{ myBasic: [] }]
}
})
}
`);
const { name: output } = tmp.fileSync({ postfix: '.yaml' });
const options = buildOptions(model, modelFile, output);
await generate(model, options, dmmf);
console.log('OpenAPI specification generated:', output);
const api = await OpenAPIParser.validate(output);
expect(api.paths?.['/user/findMany']?.['get']?.security).toHaveLength(1);
});
it('security inferred', async () => {
const { model, dmmf, modelFile } = await loadZModelAndDmmf(`
plugin openapi {
provider = '${normalizePath(path.resolve(__dirname, '../dist'))}'
securitySchemes = {
myBasic: { type: 'http', scheme: 'basic' }
}
}
model User {
id String @id
@@allow('create', true)
}
`);
const { name: output } = tmp.fileSync({ postfix: '.yaml' });
const options = buildOptions(model, modelFile, output);
await generate(model, options, dmmf);
console.log('OpenAPI specification generated:', output);
const api = await OpenAPIParser.validate(output);
expect(api.paths?.['/user/create']?.['post']?.security).toHaveLength(0);
expect(api.paths?.['/user/findMany']?.['get']?.security).toBeUndefined();
});
it('v3.1.0 fields', async () => {
const { model, dmmf, modelFile } = await loadZModelAndDmmf(`
plugin openapi {
provider = '${normalizePath(path.resolve(__dirname, '../dist'))}'
summary = 'awesome api'
}
model User {
id String @id
}
`);
const { name: output } = tmp.fileSync({ postfix: '.yaml' });
const options = buildOptions(model, modelFile, output);
await generate(model, options, dmmf);
console.log('OpenAPI specification generated:', output);
await OpenAPIParser.validate(output);
const parsed = YAML.parse(fs.readFileSync(output, 'utf-8'));
expect(parsed.openapi).toBe('3.1.0');
expect(parsed.info.summary).toEqual('awesome api');
});
it('ignored model used as relation', async () => {
const { model, dmmf, modelFile } = await loadZModelAndDmmf(`
plugin openapi {
provider = '${normalizePath(path.resolve(__dirname, '../dist'))}'
}
model User {
id String @id
email String @unique
posts Post[]
}
model Post {
id String @id
title String
author User? @relation(fields: [authorId], references: [id])
authorId String?
@@openapi.ignore()
}
`);
const { name: output } = tmp.fileSync({ postfix: '.yaml' });
const options = buildOptions(model, modelFile, output);
await generate(model, options, dmmf);
console.log('OpenAPI specification generated:', output);
await OpenAPIParser.validate(output);
});
it('field type coverage', async () => {
for (const specVersion of ['3.0.0', '3.1.0']) {
const { model, dmmf, modelFile } = await loadZModelAndDmmf(`
plugin openapi {
provider = '${normalizePath(path.resolve(__dirname, '../dist'))}'
specVersion = '${specVersion}'
}
type Meta {
something String
}
model Foo {
id String @id @default(cuid())
string String
int Int
bigInt BigInt
date DateTime
float Float
decimal Decimal
boolean Boolean
bytes Bytes?
json Meta? @json
plainJson Json
@@allow('all', true)
}
`);
const { name: output } = tmp.fileSync({ postfix: '.yaml' });
const options = buildOptions(model, modelFile, output);
await generate(model, options, dmmf);
console.log(`OpenAPI specification generated for ${specVersion}: ${output}`);
await OpenAPIParser.validate(output);
const parsed = YAML.parse(fs.readFileSync(output, 'utf-8'));
expect(parsed.openapi).toBe(specVersion);
const baseline = YAML.parse(
fs.readFileSync(`${__dirname}/baseline/rpc-type-coverage-${specVersion}.baseline.yaml`, 'utf-8')
);
expect(parsed).toMatchObject(baseline);
}
});
it('complex TypeDef structures', async () => {
for (const specVersion of ['3.0.0', '3.1.0']) {
const { model, dmmf, modelFile } = await loadZModelAndDmmf(`
plugin openapi {
provider = '${normalizePath(path.resolve(__dirname, '../dist'))}'
specVersion = '${specVersion}'
}
enum Status {
PENDING
APPROVED
REJECTED
}
type Address {
street String
city String
country String
zipCode String?
}
type ContactInfo {
email String
phone String?
addresses Address[]
}
type ReviewItem {
id String
status Status
reviewer ContactInfo
score Int
comments String[]
metadata Json?
}
type ComplexData {
reviews ReviewItem[]
primaryContact ContactInfo
tags String[]
settings Json
}
model Product {
id String @id @default(cuid())
name String
data ComplexData @json
simpleJson Json
@@allow('all', true)
}
`);
const { name: output } = tmp.fileSync({ postfix: '.yaml' });
const options = buildOptions(model, modelFile, output);
await generate(model, options, dmmf);
await OpenAPIParser.validate(output);
const parsed = YAML.parse(fs.readFileSync(output, 'utf-8'));
expect(parsed.openapi).toBe(specVersion);
// Verify all TypeDefs are generated
expect(parsed.components.schemas.Address).toBeDefined();
expect(parsed.components.schemas.ContactInfo).toBeDefined();
expect(parsed.components.schemas.ReviewItem).toBeDefined();
expect(parsed.components.schemas.ComplexData).toBeDefined();
// Verify enum reference in TypeDef
expect(parsed.components.schemas.ReviewItem.properties.status.$ref).toBe('#/components/schemas/Status');
// Json field inside a TypeDef should remain generic (wrapped with nullable since it's optional)
// OpenAPI 3.1 uses oneOf with null type, while 3.0 uses nullable: true
if (specVersion === '3.1.0') {
expect(parsed.components.schemas.ReviewItem.properties.metadata).toEqual({
oneOf: [
{ type: 'null' },
{}
]
});
} else {
expect(parsed.components.schemas.ReviewItem.properties.metadata).toEqual({ nullable: true });
}
// Verify nested TypeDef references
expect(parsed.components.schemas.ContactInfo.properties.addresses.type).toBe('array');
expect(parsed.components.schemas.ContactInfo.properties.addresses.items.$ref).toBe('#/components/schemas/Address');
// Verify array of complex objects
expect(parsed.components.schemas.ComplexData.properties.reviews.type).toBe('array');
expect(parsed.components.schemas.ComplexData.properties.reviews.items.$ref).toBe('#/components/schemas/ReviewItem');
// Verify the Product model references the ComplexData TypeDef
expect(parsed.components.schemas.Product.properties.data.$ref).toBe('#/components/schemas/ComplexData');
// Verify plain Json field remains generic
expect(parsed.components.schemas.Product.properties.simpleJson).toEqual({});
}
});
it('array of TypeDef with enum directly on model field', async () => {
for (const specVersion of ['3.0.0', '3.1.0']) {
const { model, dmmf, modelFile } = await loadZModelAndDmmf(`
plugin openapi {
provider = '${normalizePath(path.resolve(__dirname, '../dist'))}'
specVersion = '${specVersion}'
}
enum Language {
FR
EN
ES
DE
IT
}
type TranslatedField {
language Language
content String
}
model Article {
id String @id @default(cuid())
title TranslatedField[] @json
description TranslatedField[] @json
@@allow('all', true)
}
`);
const { name: output } = tmp.fileSync({ postfix: '.yaml' });
const options = buildOptions(model, modelFile, output);
await generate(model, options, dmmf);
await OpenAPIParser.validate(output);
const parsed = YAML.parse(fs.readFileSync(output, 'utf-8'));
expect(parsed.openapi).toBe(specVersion);
// Verify TranslatedField TypeDef is generated
expect(parsed.components.schemas.TranslatedField).toBeDefined();
// Verify Language enum is generated
expect(parsed.components.schemas.Language).toBeDefined();
// Verify enum reference inside TranslatedField
expect(parsed.components.schemas.TranslatedField.properties.language.$ref).toBe('#/components/schemas/Language');
// Verify array of TypeDef directly on model field
expect(parsed.components.schemas.Article.properties.title.type).toBe('array');
expect(parsed.components.schemas.Article.properties.title.items.$ref).toBe('#/components/schemas/TranslatedField');
// Verify second array field as well
expect(parsed.components.schemas.Article.properties.description.type).toBe('array');
expect(parsed.components.schemas.Article.properties.description.items.$ref).toBe('#/components/schemas/TranslatedField');
}
});
it('full-text search', async () => {
const { model, dmmf, modelFile } = await loadZModelAndDmmf(`
generator js {
provider = 'prisma-client-js'
previewFeatures = ['fullTextSearch']
}
plugin openapi {
provider = '${normalizePath(path.resolve(__dirname, '../dist'))}'
}
enum role {
USER
ADMIN
}
model User {
id String @id
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
email String @unique
role role @default(USER)
posts post_Item[]
}
model post_Item {
id String @id
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
title String
author User? @relation(fields: [authorId], references: [id])
authorId String?
published Boolean @default(false)
viewCount Int @default(0)
}
`);
const { name: output } = tmp.fileSync({ postfix: '.yaml' });
const options = buildOptions(model, modelFile, output);
await generate(model, options, dmmf);
console.log('OpenAPI specification generated:', output);
await OpenAPIParser.validate(output);
});
it('auth() in @default()', async () => {
const { projectDir } = await loadSchema(`
plugin openapi {
provider = '${normalizePath(path.resolve(__dirname, '../dist'))}'
output = '$projectRoot/openapi.yaml'
flavor = 'rpc'
}
model User {
id Int @id
posts Post[]
}
model Post {
id Int @id
title String
author User @relation(fields: [authorId], references: [id])
authorId Int @default(auth().id)
}
`);
const output = path.join(projectDir, 'openapi.yaml');
console.log('OpenAPI specification generated:', output);
await OpenAPIParser.validate(output);
const parsed = YAML.parse(fs.readFileSync(output, 'utf-8'));
expect(parsed.components.schemas.PostCreateInput.required).not.toContain('author');
expect(parsed.components.schemas.PostCreateManyInput.required).not.toContain('authorId');
});
});
function buildOptions(model: Model, modelFile: string, output: string) {
const optionFields = model.declarations.find((d): d is Plugin => isPlugin(d))?.fields || [];
const options: any = { schemaPath: modelFile, output, flavor: 'rpc' };
optionFields.forEach((f) => (options[f.name] = getLiteral(f.value) ?? getObjectLiteral(f.value)));
return options;
}