-
Notifications
You must be signed in to change notification settings - Fork 60
/
index.ts
96 lines (85 loc) · 1.95 KB
/
index.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
import {
OpenApiGeneratorV3,
// The exact same can be achieved by importing OpenApiGeneratorV31 instead:
// OpenApiGeneratorV31
OpenAPIRegistry,
extendZodWithOpenApi,
} from '../src';
import { z } from 'zod';
import * as yaml from 'yaml';
import * as fs from 'fs';
extendZodWithOpenApi(z);
const registry = new OpenAPIRegistry();
const UserIdSchema = registry.registerParameter(
'UserId',
z.string().openapi({
param: {
name: 'id',
in: 'path',
},
example: '1212121',
})
);
const UserSchema = z
.object({
id: z.string().openapi({
example: '1212121',
}),
name: z.string().openapi({
example: 'John Doe',
}),
age: z.number().openapi({
example: 42,
}),
})
.openapi('User');
const bearerAuth = registry.registerComponent('securitySchemes', 'bearerAuth', {
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT',
});
registry.registerPath({
method: 'get',
path: '/users/{id}',
description: 'Get user data by its id',
summary: 'Get a single user',
security: [{ [bearerAuth.name]: [] }],
request: {
params: z.object({ id: UserIdSchema }),
},
responses: {
200: {
description: 'Object with user data.',
content: {
'application/json': {
schema: UserSchema,
},
},
},
204: {
description: 'No content - successful operation',
},
},
});
function getOpenApiDocumentation() {
const generator = new OpenApiGeneratorV3(registry.definitions);
return generator.generateDocument({
openapi: '3.0.0',
info: {
version: '1.0.0',
title: 'My API',
description: 'This is the API',
},
servers: [{ url: 'v1' }],
});
}
function writeDocumentation() {
// OpenAPI JSON
const docs = getOpenApiDocumentation();
// YAML equivalent
const fileContent = yaml.stringify(docs);
fs.writeFileSync(`${__dirname}/openapi-docs.yml`, fileContent, {
encoding: 'utf-8',
});
}
writeDocumentation();