-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathopenapiSpec.ts
More file actions
98 lines (91 loc) · 2.48 KB
/
openapiSpec.ts
File metadata and controls
98 lines (91 loc) · 2.48 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
import { z, AnyAPIDescription, AnyResourceConfig, allEndpoints } from "./stl";
import {
ZodOpenApiOperationObject,
ZodOpenApiPathsObject,
createDocument,
oas31,
} from "zod-openapi";
type OpenAPIObject = oas31.OpenAPIObject;
import { snakeCase } from "lodash";
function allModels(
resource:
| AnyResourceConfig
| Pick<AnyResourceConfig, "models" | "namespacedResources">
): Record<string, z.ZodTypeAny> {
return {
...resource.models,
...Object.assign(
{},
...Object.keys(resource.namespacedResources || {}).map((k) =>
allModels(resource.namespacedResources[k])
)
),
};
}
export async function openapiSpec(
apiDescription: AnyAPIDescription
): Promise<OpenAPIObject> {
const models = allModels({
models: apiDescription.topLevel?.models,
namespacedResources: apiDescription.resources,
});
for (const name in models) {
(models[name] as any)["x-stainless-modelName"] = snakeCase(name);
}
const endpoints = allEndpoints({
actions: apiDescription.topLevel?.actions,
namespacedResources: apiDescription.resources,
});
await Promise.all(endpoints.map((e) => e.stl.loadEndpointTypeSchemas(e)));
const paths: ZodOpenApiPathsObject = {};
for (const route of endpoints) {
const [httpMethod, path] = route.endpoint.split(" ", 2);
const lowerMethod = httpMethod.toLowerCase() as "get" | "post" | "delete";
const operation: ZodOpenApiOperationObject = {
summary: route.summary,
description: route.description,
requestParams: {
path: route.path,
query: route.query,
// TODO
// header: route.header,
},
requestBody: {
content: {
"application/json": {
schema: route.body,
},
},
},
responses: {
200: {
description: "success",
content: route.response
? {
"application/json": {
schema: route.response,
},
}
: {},
},
},
};
paths[path] ??= {};
paths[path][lowerMethod] = operation;
}
const document = createDocument({
openapi: "3.1.0",
info: {
version: "1.0.0",
title: "My API",
},
servers: [{ url: "v1" }],
components: {
// Cast to any because zod/v3 types are structurally compatible with zod/v4
// at runtime, but TypeScript sees them as incompatible types
schemas: models as any,
},
paths,
});
return document;
}