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
import { HttpVerb } from "https://esm.town/v/xkonti/httpUtils";
import { z } from "npm:zod";
import { zodToJsonSchema } from "npm:zod-to-json-schema";
export function getSchemaDesc(schema: z.Schema) {
return zodToJsonSchema(schema, {
name: "schema",
target: "openApi3",
}).definitions.schema;
}
export interface EndpointDefBase {
verb: HttpVerb;
path: string;
desc: string;
operationId: string;
}
export interface EndpointDefinition extends EndpointDefBase {
requestSchema: z.Schema | null;
requestDesc: string | null;
responseSchema: z.Schema | null;
responseDesc: string | null;
}
export function getPathsDesc(endpoints: EndpointDefinition[]) {
const paths: any = {};
for (const endpoint of endpoints) {
// This is to allow multiple endpoints with the same path but different verbs
if (!paths[endpoint.path]) {
paths[endpoint.path] = {};
}
paths[endpoint.path][endpoint.verb.toLowerCase()] = {
description: endpoint.desc,
operationId: endpoint.operationId,
requestBody: endpoint.requestSchema
? {
description: endpoint.requestDesc ?? "Request body",
required: true,
content: {
"application/json": {
schema: getSchemaDesc(endpoint.requestSchema),
},
},
}
: undefined,
responses: {
"200": {
description: endpoint.responseDesc ?? "Success",
content: {
"application/json": {
schema: getSchemaDesc(endpoint.responseSchema),
},
},
},
},
};
}
return paths;
}
export function getOpenApiSpec(
url: string,
title: string,
description: string,
version: string,
endpoints: EndpointDefinition[],
) {
return {
openapi: "3.1.0",
info: {
title,
description,
version,
},
servers: [
{
url,
},
],
paths: getPathsDesc(endpoints),
};
}