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) {
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),
};
}