Skip to content

Add response headers #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/mean-walls-lick.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"typed-openapi": minor
---

Add response headers in endpoint types
169 changes: 96 additions & 73 deletions packages/typed-openapi/src/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,29 +70,29 @@ export const generateFile = (options: GeneratorOptions) => {
ctx.runtime === "none"
? (file: string) => file
: (file: string) => {
const model = Codegen.TypeScriptToModel.Generate(file);
const transformer = runtimeValidationGenerator[ctx.runtime as Exclude<typeof ctx.runtime, "none">];
// tmp fix for typebox, there's currently a "// todo" only with Codegen.ModelToTypeBox.Generate
// https://github.com/sinclairzx81/typebox-codegen/blob/44d44d55932371b69f349331b1c8a60f5d760d9e/src/model/model-to-typebox.ts#L31
const generated = ctx.runtime === "typebox" ? Codegen.TypeScriptToTypeBox.Generate(file) : transformer(model);

let converted = "";
const match = generated.match(/(const __ENDPOINTS_START__ =)([\s\S]*?)(export type __ENDPOINTS_END__)/);
const content = match?.[2];

if (content && ctx.runtime in replacerByRuntime) {
const before = generated.slice(0, generated.indexOf("export type __ENDPOINTS_START"));
converted =
before +
replacerByRuntime[ctx.runtime as keyof typeof replacerByRuntime](
content.slice(content.indexOf("export")),
);
} else {
converted = generated;
}
const model = Codegen.TypeScriptToModel.Generate(file);
const transformer = runtimeValidationGenerator[ctx.runtime as Exclude<typeof ctx.runtime, "none">];
// tmp fix for typebox, there's currently a "// todo" only with Codegen.ModelToTypeBox.Generate
// https://github.com/sinclairzx81/typebox-codegen/blob/44d44d55932371b69f349331b1c8a60f5d760d9e/src/model/model-to-typebox.ts#L31
const generated = ctx.runtime === "typebox" ? Codegen.TypeScriptToTypeBox.Generate(file) : transformer(model);

let converted = "";
const match = generated.match(/(const __ENDPOINTS_START__ =)([\s\S]*?)(export type __ENDPOINTS_END__)/);
const content = match?.[2];

if (content && ctx.runtime in replacerByRuntime) {
const before = generated.slice(0, generated.indexOf("export type __ENDPOINTS_START"));
converted =
before +
replacerByRuntime[ctx.runtime as keyof typeof replacerByRuntime](
content.slice(content.indexOf("export")),
);
} else {
converted = generated;
}

return converted;
};
return converted;
};

const file = `
${transform(schemaList + endpointSchemaList)}
Expand Down Expand Up @@ -132,6 +132,24 @@ const parameterObjectToString = (parameters: Box<AnyBoxDef> | Record<string, Any
}
return str + "}";
};

const responseHeadersObjectToString = (responseHeaders: Record<string, AnyBox>, ctx: GeneratorContext) => {
let str = "{";
for (const [key, responseHeader] of Object.entries(responseHeaders)) {
const value = ctx.runtime === "none"
? responseHeader.recompute((box) => {
if (Box.isReference(box) && !box.params.generics && box.value !== "null") {
box.value = `Schemas.${box.value}`;
}

return box;
}).value
: responseHeader.value
str += `${wrapWithQuotesIfNeeded(key.toLowerCase())}: ${value},\n`;
}
return str + "}";
}

const generateEndpointSchemaList = (ctx: GeneratorContext) => {
let file = `
${ctx.runtime === "none" ? "export namespace Endpoints {" : ""}
Expand All @@ -145,39 +163,42 @@ const generateEndpointSchemaList = (ctx: GeneratorContext) => {
path: "${endpoint.path}",
requestFormat: "${endpoint.requestFormat}",
${
endpoint.meta.hasParameters
? `parameters: {
endpoint.meta.hasParameters
? `parameters: {
${parameters.query ? `query: ${parameterObjectToString(parameters.query)},` : ""}
${parameters.path ? `path: ${parameterObjectToString(parameters.path)},` : ""}
${parameters.header ? `header: ${parameterObjectToString(parameters.header)},` : ""}
${
parameters.body
? `body: ${parameterObjectToString(
ctx.runtime === "none"
? parameters.body.recompute((box) => {
if (Box.isReference(box) && !box.params.generics) {
box.value = `Schemas.${box.value}`;
}
return box;
})
: parameters.body,
)},`
ctx.runtime === "none"
? parameters.body.recompute((box) => {
if (Box.isReference(box) && !box.params.generics) {
box.value = `Schemas.${box.value}`;
}
return box;
})
: parameters.body,
)},`
: ""
}
}`
: "parameters: never,"
}
: "parameters: never,"
}
response: ${
ctx.runtime === "none"
? endpoint.response.recompute((box) => {
if (Box.isReference(box) && !box.params.generics && box.value !== "null") {
box.value = `Schemas.${box.value}`;
}

return box;
}).value
: endpoint.response.value
},
ctx.runtime === "none"
? endpoint.response.recompute((box) => {
if (Box.isReference(box) && !box.params.generics && box.value !== "null") {
box.value = `Schemas.${box.value}`;
}

return box;
}).value
: endpoint.response.value
},
${
endpoint.responseHeaders ? `responseHeaders: ${responseHeadersObjectToString(endpoint.responseHeaders, ctx)},` : ""
}
}\n`;
});

Expand All @@ -199,14 +220,14 @@ const generateEndpointByMethod = (ctx: GeneratorContext) => {
// <EndpointByMethod>
export ${ctx.runtime === "none" ? "type" : "const"} EndpointByMethod = {
${Object.entries(byMethods)
.map(([method, list]) => {
return `${method}: {
.map(([method, list]) => {
return `${method}: {
${list.map(
(endpoint) => `"${endpoint.path}": ${ctx.runtime === "none" ? "Endpoints." : ""}${endpoint.meta.alias}`,
)}
(endpoint) => `"${endpoint.path}": ${ctx.runtime === "none" ? "Endpoints." : ""}${endpoint.meta.alias}`,
)}
}`;
})
.join(",\n")}
})
.join(",\n")}
}
${ctx.runtime === "none" ? "" : "export type EndpointByMethod = typeof EndpointByMethod;"}
// </EndpointByMethod>
Expand All @@ -216,8 +237,8 @@ const generateEndpointByMethod = (ctx: GeneratorContext) => {

// <EndpointByMethod.Shorthands>
${Object.keys(byMethods)
.map((method) => `export type ${capitalize(method)}Endpoints = EndpointByMethod["${method}"]`)
.join("\n")}
.map((method) => `export type ${capitalize(method)}Endpoints = EndpointByMethod["${method}"]`)
.join("\n")}
// </EndpointByMethod.Shorthands>
`;

Expand Down Expand Up @@ -246,6 +267,7 @@ type RequestFormat = "json" | "form-data" | "form-url" | "binary" | "text";
export type DefaultEndpoint = {
parameters?: EndpointParameters | undefined;
response: unknown;
responseHeaders?: Record<string, unknown>;
};

export type Endpoint<TConfig extends DefaultEndpoint = DefaultEndpoint> = {
Expand All @@ -260,6 +282,7 @@ export type Endpoint<TConfig extends DefaultEndpoint = DefaultEndpoint> = {
areParametersRequired: boolean;
};
response: TConfig["response"];
responseHeaders?: TConfig["responseHeaders"]
};

export type Fetcher = (method: Method, url: string, parameters?: EndpointParameters | undefined) => Promise<Response>;
Expand Down Expand Up @@ -303,18 +326,18 @@ export class ApiClient {
${method}<Path extends keyof ${capitalizedMethod}Endpoints, TEndpoint extends ${capitalizedMethod}Endpoints[Path]>(
path: Path,
...params: MaybeOptionalArg<${match(ctx.runtime)
.with("zod", "yup", () => infer(`TEndpoint["parameters"]`))
.with("arktype", "io-ts", "typebox", "valibot", () => infer(`TEndpoint`) + `["parameters"]`)
.otherwise(() => `TEndpoint["parameters"]`)}>
.with("zod", "yup", () => infer(`TEndpoint["parameters"]`))
.with("arktype", "io-ts", "typebox", "valibot", () => infer(`TEndpoint`) + `["parameters"]`)
.otherwise(() => `TEndpoint["parameters"]`)}>
): Promise<${match(ctx.runtime)
.with("zod", "yup", () => infer(`TEndpoint["response"]`))
.with("arktype", "io-ts", "typebox", "valibot", () => infer(`TEndpoint`) + `["response"]`)
.otherwise(() => `TEndpoint["response"]`)}> {
.with("zod", "yup", () => infer(`TEndpoint["response"]`))
.with("arktype", "io-ts", "typebox", "valibot", () => infer(`TEndpoint`) + `["response"]`)
.otherwise(() => `TEndpoint["response"]`)}> {
return this.fetcher("${method}", this.baseUrl + path, params[0])
.then(response => this.parseResponse(response))${match(ctx.runtime)
.with("zod", "yup", () => `as Promise<${infer(`TEndpoint["response"]`)}>`)
.with("arktype", "io-ts", "typebox", "valibot", () => `as Promise<${infer(`TEndpoint`) + `["response"]`}>`)
.otherwise(() => `as Promise<TEndpoint["response"]>`)};
.with("zod", "yup", () => `as Promise<${infer(`TEndpoint["response"]`)}>`)
.with("arktype", "io-ts", "typebox", "valibot", () => `as Promise<${infer(`TEndpoint`) + `["response"]`}>`)
.otherwise(() => `as Promise<TEndpoint["response"]>`)};
}
// </ApiClient.${method}>
`
Expand All @@ -334,17 +357,17 @@ export class ApiClient {
method: TMethod,
path: TPath,
...params: MaybeOptionalArg<${match(ctx.runtime)
.with("zod", "yup", () =>
inferByRuntime[ctx.runtime](`TEndpoint extends { parameters: infer Params } ? Params : never`),
)
.with(
"arktype",
"io-ts",
"typebox",
"valibot",
() => inferByRuntime[ctx.runtime](`TEndpoint`) + `["parameters"]`,
)
.otherwise(() => `TEndpoint extends { parameters: infer Params } ? Params : never`)}>)
.with("zod", "yup", () =>
inferByRuntime[ctx.runtime](`TEndpoint extends { parameters: infer Params } ? Params : never`),
)
.with(
"arktype",
"io-ts",
"typebox",
"valibot",
() => inferByRuntime[ctx.runtime](`TEndpoint`) + `["parameters"]`,
)
.otherwise(() => `TEndpoint extends { parameters: infer Params } ? Params : never`)}>)
: Promise<Omit<Response, "json"> & {
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json) */
json: () => Promise<TEndpoint extends { response: infer Res } ? Res : never>;
Expand Down
14 changes: 13 additions & 1 deletion packages/typed-openapi/src/map-openapi-endpoints.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,16 @@ export const mapOpenApiEndpoints = (doc: OpenAPIObject) => {
}
}

// Map response headers
const headers = responseObject?.headers;
if (headers) {
endpoint.responseHeaders = Object.entries(headers).reduce((acc, [name, headerOrRef]) => {
const header = refs.unwrap(headerOrRef);
acc[name] = openApiSchemaToTs({ schema: header.schema ?? {}, ctx });
return acc;
}, {} as Record<string, Box>);
}

endpointList.push(endpoint);
});
});
Expand Down Expand Up @@ -184,6 +194,7 @@ type RequestFormat = "json" | "form-data" | "form-url" | "binary" | "text";
type DefaultEndpoint = {
parameters?: EndpointParameters | undefined;
response: AnyBox;
responseHeaders?: Record<string, AnyBox>
};

export type Endpoint<TConfig extends DefaultEndpoint = DefaultEndpoint> = {
Expand All @@ -198,4 +209,5 @@ export type Endpoint<TConfig extends DefaultEndpoint = DefaultEndpoint> = {
areParametersRequired: boolean;
};
response: TConfig["response"];
};
responseHeaders?: TConfig["responseHeaders"];
};
2 changes: 1 addition & 1 deletion packages/typed-openapi/tests/generate-runtime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const samples = ["petstore", "docker.openapi", "long-operation-id"];
const runtimes = allowedRuntimes.toJsonSchema().enum;

samples.forEach((sample) => {
describe(`generate-rutime-${sample}`, async () => {
describe(`generate-runtime-${sample}`, async () => {
const filePath = `${__dirname}/samples/${sample}.yaml`;
const openApiDoc = (await SwaggerParser.parse(filePath)) as OpenAPIObject;
const ctx = mapOpenApiEndpoints(openApiDoc);
Expand Down
7 changes: 7 additions & 0 deletions packages/typed-openapi/tests/generator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,7 @@ describe("generator", () => {
query: Partial<{ username: string; password: string }>;
};
response: string;
responseHeaders: { "X-Rate-Limit": number; "X-Expires-After": string };
};
export type get_LogoutUser = {
method: "GET";
Expand Down Expand Up @@ -283,6 +284,7 @@ describe("generator", () => {
export type DefaultEndpoint = {
parameters?: EndpointParameters | undefined;
response: unknown;
responseHeaders?: Record<string, unknown>;
};

export type Endpoint<TConfig extends DefaultEndpoint = DefaultEndpoint> = {
Expand All @@ -297,6 +299,7 @@ describe("generator", () => {
areParametersRequired: boolean;
};
response: TConfig["response"];
responseHeaders?: TConfig["responseHeaders"];
};

export type Fetcher = (method: Method, url: string, parameters?: EndpointParameters | undefined) => Promise<Response>;
Expand Down Expand Up @@ -718,6 +721,7 @@ describe("generator", () => {
export type DefaultEndpoint = {
parameters?: EndpointParameters | undefined;
response: unknown;
responseHeaders?: Record<string, unknown>;
};

export type Endpoint<TConfig extends DefaultEndpoint = DefaultEndpoint> = {
Expand All @@ -732,6 +736,7 @@ describe("generator", () => {
areParametersRequired: boolean;
};
response: TConfig["response"];
responseHeaders?: TConfig["responseHeaders"];
};

export type Fetcher = (method: Method, url: string, parameters?: EndpointParameters | undefined) => Promise<Response>;
Expand Down Expand Up @@ -928,6 +933,7 @@ describe("generator", () => {
export type DefaultEndpoint = {
parameters?: EndpointParameters | undefined;
response: unknown;
responseHeaders?: Record<string, unknown>;
};

export type Endpoint<TConfig extends DefaultEndpoint = DefaultEndpoint> = {
Expand All @@ -942,6 +948,7 @@ describe("generator", () => {
areParametersRequired: boolean;
};
response: TConfig["response"];
responseHeaders?: TConfig["responseHeaders"];
};

export type Fetcher = (method: Method, url: string, parameters?: EndpointParameters | undefined) => Promise<Response>;
Expand Down
10 changes: 10 additions & 0 deletions packages/typed-openapi/tests/map-openapi-endpoints.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2297,6 +2297,16 @@ describe("map-openapi-endpoints", () => {
"type": "keyword",
"value": "string",
},
"responseHeaders": {
"X-Expires-After": {
"type": "keyword",
"value": "string",
},
"X-Rate-Limit": {
"type": "keyword",
"value": "number",
},
},
},
{
"meta": {
Expand Down
Loading