8000 feat: Add `NoResponse` helper · aklinker1/zeta@667fa82 · GitHub
[go: up one dir, main page]

Skip to content

Commit 667fa82

Browse files
committed
feat: Add NoResponse helper
1 parent 1262456 commit 667fa82

8 files changed

Lines changed: 143 additions & 31 deletions

File tree

‎example.ts‎

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
1-
import { createApp } from "./src";
1+
import {
2+
createApp,
3+
ErrorResponse,
4+
NoResponse,
5+
HttpStatus,
6+
NotFoundHttpError,
7+
} from "./src";
28
import { version } from "./package.json" with { type: "json" };
39
import { z } from "zod/v4";
4-
import { NotFoundHttpError } from "./src/errors";
510
import { zodSchemaAdapter } from "./src/adapters/zod-schema-adapter";
6-
import { HttpStatus } from "./src/status";
7-
import { ErrorResponse } from "./src/error-response";
811

912
const Entry = z.object({
1013
id: z.number(),
@@ -98,6 +101,27 @@ const app = createApp({
98101
return status(HttpStatus.Ok, entry);
99102
},
100103
)
104+
.delete(
105+
"/api/entries/:id",
106+
{
107+
operationId: "deleteEntry",
108+
summary: "Delete Entry",
109+
tags: ["Entries"],
110+
params: z.object({ id: z.coerce.number() }),
111+
responses: {
112+
[HttpStatus.NoContent]: NoResponse.meta({
113+
responseDescription: "Entry deleted",
114+
}),
115+
},
116+
},
117+
({ status, params }) => {
118+
const index = entries.findIndex((entry) => entry.id === params.id);
119+
if (index >= 0) {
120+
entries.splice(index, 1);
121+
}
122+
return status(HttpStatus.NoContent, undefined);
123+
},
124+
)
101125
.get(
102126
"/api/csv",
103127
{

‎src/__tests__/types.test.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { expectTypeOf } from "expect-type";
33
import type * as t from "../types";
44
import { z } from "zod/v4";
55
import type { StandardSchemaV1 } from "@standard-schema/spec";
6-
import type { ErrorResponse } from "../error-response";
6+
import { ErrorResponse } from "../custom-responses";
77

88
describe("Types", () => {
99
describe("MergeRoutes", () => {
@@ -155,7 +155,7 @@ describe("Types", () => {
155155
body: z.ZodObject<{ id: z.ZodString; user: z.ZodString }>;
156156
responses: {
157157
200: z.ZodArray<z.ZodObject<{ id: z.ZodString; user: z.ZodString }>>;
158-
400: ErrorResponse;
158+
400: typeof ErrorResponse;
159159
};
160160
};
161161
type Expected = {
@@ -440,7 +440,7 @@ describe("Types", () => {
440440
query: z.ZodObject<{ query: z.ZodNumber }>;
441441
params: z.ZodObject<{ params: z.ZodBoolean }>;
442442
responses: {
443-
404: ErrorResponse;
443+
404: typeof ErrorResponse;
444444
};
445445
};
446446
type Ctx = { a: "A" };

‎src/app.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,9 +107,15 @@ export function createApp<TPrefix extends BasePrefix = "">(
107107
const jsonRoute = options?.openApiRoute ?? "/openapi.json";
108108
const scalarRoute = options?.scalarRoute ?? "/scalar";
109109
const docs = buildOpenApiDocs(options, app);
110+
if (docs.type === "error") {
111+
console.error("Failed to build OpenAPI docs:", docs.error);
112+
}
110113

111114
app.get(jsonRoute, () => {
112-
if (docs.type === "error") throw docs.error;
115+
if (docs.type === "error") {
116+
console.error("Failed to build OpenAPI docs:", docs.error);
117+
throw docs.error;
118+
}
113119
return docs.docs;
114120
});
115121
if (docs.type === "success") {

‎src/client.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import type {
88
GetRequestParamsInput,
99
GetResponseOutput,
1010
} from "./types";
11-
import type { ErrorResponse } from "./error-response";
11+
import type { ErrorResponse } from "./custom-responses";
1212
import { smartDeserialize, smartSerialize } from "./internal/serialization";
1313
import type {
1414
GetAppRoutes,
Lines changed: 78 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,45 @@
11
import type { StandardSchemaV1 } from "@standard-schema/spec";
22
import type { HttpStatus } from "./status";
33

4+
export type ZetaSchema<Input = unknown, Output = Input> = StandardSchemaV1<
5+
Input,
6+
Output
7+
> & {
8+
"~zeta": {
9+
type: string;
10+
meta: Record<string, any>;
11+
};
12+
meta(meta?: Record<string, any>): ZetaSchema<Input, Output>;
13+
};
14+
15+
function createZetaSchema<Input = unknown, Output = Input>(
16+
name: string,
17+
validate: (value: unknown) => StandardSchemaV1.Result<Output>,
18+
meta: Record<string, string> = {},
19+
): ZetaSchema<Input, Output> {
20+
const parentMeta = meta;
21+
return {
22+
"~zeta": {
23+
type: name,
24+
meta,
25+
},
26+
"~standard": {
27+
vendor: "@aklinker/zeta",
28+
version: 1,
29+
validate,
30+
},
31+
meta(meta) {
32+
return createZetaSchema(name, validate, {
33+
...parentMeta,
34+
...meta,
35+
});
36+
},
37+
};
38+
}
39+
440
/**
5-
* A schema for a error response. Use when defining additional status codes that an operation might return with:
41+
* A schema for an error response. Use when defining additional status codes
42+
* that an operation might return with:
643
*
744
* ```ts
845
* import { ErrorResponse } from '@aklinker/zeta';
@@ -21,11 +58,10 @@ import type { HttpStatus } from "./status";
2158
* );
2259
* ```
2360
*/
24-
export const ErrorResponse: StandardSchemaV1 = {
25-
"~standard": {
26-
vendor: "@aklinker/zeta",
27-
version: 1,
28-
validate: (value: unknown): StandardSchemaV1.Result<ErrorResponse> => {
61+
export const ErrorResponse: ZetaSchema<unknown, ErrorResponse> =
62+
createZetaSchema<unknown, ErrorResponse>(
63+
"ErrorResponse",
64+
(value: unknown): StandardSchemaV1.Result<ErrorResponse> => {
2965
if (value == null)
3066
return {
3167
issues: [{ message: `Expected an object, received ${value}` }],
@@ -59,13 +95,12 @@ export const ErrorResponse: StandardSchemaV1 = {
5995

6096
return { value: value as ErrorResponse };
6197
},
62-
},
63-
};
98+
);
6499

65100
/**
66101
* The actual type an error response conforms to.
67102
*/
68-
export type ErrorResponse = StandardSchemaV1 & {
103+
export type ErrorResponse = {
69104
[additionalInfo: string]: any;
70105
name: string;
71106
message: string;
@@ -95,3 +130,37 @@ export const ErrorResponseJsonSchema = {
95130
},
96131
required: ["status", "name", "message"],
97132
};
133+
134+
/**
135+
* A schema for when you want to not return a response. Use when defining
136+
* additional status codes that an operation might return with:
137+
*
138+
* ```ts
139+
* import { NoResponse } from '@aklinker/zeta';
140+
*
141+
* app.get(
142+
* "/api/item/:itemId",
143+
* {
144+
* responses: {
145+
* [HttpStatus.Accepted]: NoResponse,
146+
* }
147+
* },
148+
* () => {
149+
* // ...
150+
* }
151+
* );
152+
* ```
153+
*/
154+
export const NoResponse: ZetaSchema<undefined | null | void, void> =
155+
createZetaSchema<undefined | null | void, void>(
156+
"NoResponse",
157+
(value: unknown): StandardSchemaV1.Result<void> => {
158+
return value != null
159+
? {
160+
issues: [
161+
{ message: `Expected undefined or null, got ${typeof value}` },
162+
],
163+
}
164+
: { value: undefined };
165+
},
166+
);

‎src/index.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
export * from "./app";
22
export type { App } from "./types";
3-
export { ErrorResponse } from "./error-response";
3+
export { ErrorResponse, NoResponse, type ZetaSchema } from "./custom-responses";
44
export * from "./status";
55
export * from "./errors";

‎src/internal/utils.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import type {
99
StatusResult,
1010
} from "../types";
1111
import type { MatchedRoute } from "rou3";
12-
import { ErrorResponse } from "../error-response";
12+
import type { ErrorResponse } from "../custom-responses";
1313

1414
export function validateSchema<T>(
1515
schema: StandardSchemaV1<T, T>,

‎src/open-api.ts‎

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import type { App, BasePath, SchemaAdapter } from "./types";
33
import type { CreateAppOptions } from "./app";
44
import type { StandardSchemaV1 } from "@standard-schema/spec";
55
import { getHttpStatusName } from "./status";
6-
import { ErrorResponseJsonSchema } from "./error-response";
6+
import { ErrorResponseJsonSchema, type ZetaSchema } from "./custom-responses";
77

88
export function buildOpenApiDocs(
99
options: CreateAppOptions<any> | undefined,
@@ -39,6 +39,7 @@ export function buildOpenApiDocs(
3939
routerData.def ?? {};
4040
docs.paths ??= {};
4141
docs.paths[openApiPath] ??= {};
42+
4243
(docs.paths[openApiPath] as any)[method.toLowerCase()] = {
4344
...openApiOperation,
4445
requestBody: body
@@ -146,20 +147,32 @@ function mapParameters(
146147

147148
function buildResponse(
148149
status: number,
149-
schema: StandardSchemaV1,
150+
schema: StandardSchemaV1 | ZetaSchema,
150151
adapter: SchemaAdapter,
151152
): NonNullable<OpenAPI.Operation["responses"]>[string] {
152-
if (status >= 400)
153-
return {
154-
description: getHttpStatusName(status) ?? "",
155-
content: {
156-
"application/json": {
157-
schema: {
158-
$ref: "#/components/schemas/ErrorResponse",
153+
if ("~zeta" in schema) {
154+
const description =
155+
schema["~zeta"].meta?.responseDescription ??
156+
getHttpStatusName(status) ??
157+
"";
158+
if (schema["~zeta"].type === "NoResponse") {
159+
return {
160+
description,
161+
};
162+
}
163+
if (schema["~zeta"].type === "ErrorResponse") {
164+
return {
165+
description,
166+
content: {
167+
"application/json": {
168+
schema: {
169+
$ref: "#/components/schemas/ErrorResponse",
170+
},
159171
},
160172
},
161-
},
162-
};
173+
};
174+
}
175+
}
163176

164177
const meta = adapter.getMeta(schema);
165178
return {

0 commit comments

Comments
 (0)
0