FFFF feat!: Multiple responses · aklinker1/zeta@69ba98a · GitHub
[go: up one dir, main page]

Skip to content

Commit 69ba98a

Browse files
committed
feat!: Multiple responses
Breaking changes: - When defining an endpoint, `response` was renamed to `responses` - `onGlobalError` no longer supports a return type. Zeta converts all errors into responses automatically - Fix typo in type name: `OnGlobalErrorHoos` → `OnGlobalErrorHooks` - `@aklinker1/zeta/status` is merged into `@aklinker1/zeta`
1 parent 8a45caa commit 69ba98a

16 files changed

Lines changed: 591 additions & 136 deletions

‎CHANGELOG.md‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,11 @@
66

77
### 🏡 Chore
88

9-
- ⚠️ Generalize the `getResponseContentType` adapter method to `getMeta` ([246519b](https://github.com/aklinker1/zeta/commit/246519b))
9+
- ⚠️ Generalize the `getResponseContentType` adapter method to `getMeta` ([246519b](https://github.com/aklinker1/zeta/commit/246519b))
1010

1111
#### ⚠️ Breaking Changes
1212

13-
- ⚠️ Generalize the `getResponseContentType` adapter method to `getMeta` ([246519b](https://github.com/aklinker1/zeta/commit/246519b))
13+
- ⚠️ Generalize the `getResponseContentType` adapter method to `getMeta` ([246519b](https://github.com/aklinker1/zeta/commit/246519b))
1414

1515
### ❤️ Contributors
1616

@@ -20,7 +20,7 @@
2020

2121
### 🚀 Enhancements
2222

23-
- ⚠️ Allow customizing the response content type on OpenAPI docs ([2721e7f](https://github.com/aklinker1/zeta/commit/2721e7f))
23+
- ⚠️ Allow customizing the response content type on OpenAPI docs ([2721e7f](https://github.com/aklinker1/zeta/commit/2721e7f))
2424

2525
### 📖 Documentation
2626

@@ -32,7 +32,7 @@
3232

3333
#### ⚠️ Breaking Changes
3434

35-
- ⚠️ Allow customizing the response content type on OpenAPI docs ([2721e7f](https://github.com/aklinker1/zeta/commit/2721e7f))
35+
- ⚠️ Allow customizing the response content type on OpenAPI docs ([2721e7f](https://github.com/aklinker1/zeta/commit/2721e7f))
3636

3737
### ❤️ Contributors
3838

‎README.md‎

Lines changed: 78 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -247,15 +247,19 @@ const app = createApp().post(
247247

248248
### Response
249249

250-
Right now, you can only define a single response schema. By default, a `200 OK` status code is returned.
250+
You can either define a single response or multiple responses.
251+
252+
For single response schemas, a `200 OK` status code is assumed.
251253

252254
```ts
253255
import { z } from "zod";
254256

255257
const app = createApp().get(
256258
"/api/health",
257259
{
258-
response: z.object({
260+
// Note: The property key is always responses (plural), even when defining a
261+
// single response schema.
262+
responses: z.object({
259263
status: z.literal("up"),
260264
version: z.string(),
261265
}),
@@ -264,27 +268,78 @@ const app = createApp().get(
264268
);
265269
```
266270

267-
When a response schema is defined, the return value from the function is type-safe. If you want to return a custom status code or headers, you can do so with the `set` function provided by the context:
271+
When defining multiple schemas for different status codes, instead of returning the value directly, you'll need to return the value of the `status` function:
268272

269273
```ts
270-
import { HttpStatus } from "@aklinker1/zeta/status";
274+
import { ErrorResponse, createApp, Status } from "@aklinker1/zeta";
275+
import { NotFoundError } from "@aklinker1/zeta/errors";
271276

272-
const app = createApp().get("/path", {}, ({ set }) => {
273-
set.status = HttpStatus.Created;
274-
set.headers["X-Example"] = "some-value";
275-
});
277+
const app = createApp().post(
278+
"/api/users",
279+
{
280+
body: UserSchema,
281+
responses: {
282+
[Status.Created]: User,
283+
[Status.Conflict]: ErrorResponse,
284+
},
285+
},
286+
async ({ status, body }) => {
287+
const userExists = await db.doesUserExist(body.email);
288+
289+
// For error responses, throwing is the recommended approach.
290+
// Zeta maps the HttpError's status code to the correct response schema.
291+
if (userExists) {
292+
throw new HttpError(
293+
Status.Conflict,
294+
"A user with this email already exists.",
295+
);
296+
}
297+
298+
const newUser = await db.createUser(body);
299+
300+
return status(Status.Created, newUser);
301+
},
302+
);
276303
```
277304

278-
> As of right now, you can't add custom status codes to the OpenAPI docs or as apart of the response schema. The OpenAPI spec will always show `200 OK` as the response.
305+
> When defining custom error responses, use `ErrorResponse` schema from `@aklinker1/zeta`.
306+
307+
When a response schema(s) are defined, the return value from the function is type-safe.
308+
309+
#### Custom Content Types
279310

280-
By default, Zeta will show `application/json` as the content type in the OpenAPI docs. you can override this by setting the `contentType` metadata on your schema:
311+
By default, Zeta will use `application/json` as the content type in the OpenAPI docs. you can override this by setting the `contentType` metadata on your schema:
281312

282313
```ts
283-
app.get("/csv", {
284-
response: z.string().meta({ contentType: "text/csv" })
285-
}, () => "...")
314+
app.get(
315+
"/csv",
316+
{
317+
responses: z.string().meta({ contentType: "text/csv" }),
318+
},
319+
() => {
320+
// ...
321+
},
322+
);
286323
```
287324

325+
> [!WARNING]
326+
>
327+
> Zeta ignores this metadata when building the response. Make sure to set the `Content-Type` header in your handler:
328+
>
329+
> ```ts
330+
> app.get(
331+
> "/csv",
332+
> {
333+
> responses: z.string().meta({ contentType: "text/csv" }),
334+
> },
335+
> ({ set }) => {
336+
> // ...
337+
> set.headers["Content-Type"] = "text/csv";
338+
> return "...";
339+
> },
340+
> );
341+
> ```
342+
288343
## Life Cycle Hooks
289344
290345
You can use any of the following APIs to hook into the request lifecycle:
@@ -327,7 +382,7 @@ graph LR
327382
- If a `Response` value is not returned, Zeta infers the response content type based on the handler's response value.
328383
- `onGlobalAfterResponse`: Called after the response is sent to the client.
329384
- Return value is ignored.
330-
- `onGlobalError`: If an error is thrown at any point in the lifecycle (other than `onGlobalAfterResponse`), this hook will be called giving you the opportunity to report the error or change the response format by optionally returning a `Response` object.
385+
- `onGlobalError`: If an error is thrown at any point in the lifecycle, this hook will be called giving you the opportunity to report the error.
331386

332387
There are two types of hooks: global and isolated.
333388

@@ -346,7 +401,10 @@ const usersApp = createApp({ prefix: "/api/users" })
346401
})
347402
.onTransform(({ path }) => {
348403
return {
349-
path: { ...path, userId: Number(path.userId) },
404+
path: {
405+
...path,
406+
userId: Number(path.userId),
407+
},
350408
};
351409
})
352410
.onBeforeHandle(async ({ path }) => {
@@ -561,10 +619,10 @@ By default, Zeta provides built-in error handling. It also provides useful error
561619

562620
```ts
563621
import { HttpError } from "@aklinker1/zeta/errors";
564-
import { HttpStatus } from "@aklinker1/zeta/status";
622+
import { Status } from "@aklinker1/zeta/status";
565623

566624
const app = createApp().get("/users", {}, () => {
567-
throw new HttpError(HttpStatus.NotImplemented, "TODO");
625+
throw new HttpError(Status.NotImplemented, "TODO");
568626
});
569627
```
570628

@@ -604,7 +662,7 @@ When a non-`HttpError` value is thrown, Zeta returns a `500 Internal Server Erro
604662
Zeta provides an enum of all HTTP status codes. You should use this instead of literal values.
605663

606664
```diff
607-
import { HttpStatus } from "@aklinker1/zeta/status";
665+
import { Status } from "@aklinker1/zeta/status";
608666

609667
const app = createApp()
610668
.post(
@@ -613,7 +671,7 @@ const app = createApp()
613671
({ set }) => {
614672
// ...
615673
- set.status = 201;
616-
+ set.status = HttpStatus.Created;
674+
+ set.status = Status.Created;
617675
},
618676
);
619677
```
@@ -688,7 +746,7 @@ expect(response).toEqual([...]);
688746
await expect(
689747
() => client.fetch("GET", "/users/123", {})
690748
).rejects.toEqual({
691-
status: HttpStatus.NotFound,
749+
status: Status.NotFound,
692750
message: "User not found",
693751
})
694752
```

‎example.ts‎

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { z } from "zod/v4";
44
import { NotFoundError } from "./src/errors";
55
import { zodSchemaAdapter } from "./src/adapters/zod-schema-adapter";
66
import { Status } from "./src/status";
7+
import { ErrorResponse } from "./src/error-response";
78

89
const Entry = z.object({
910
id: z.number(),
@@ -40,7 +41,7 @@ const app = createApp({
4041
summary: "Health check",
4142
description: "Check if the server is healthy",
4243
tags: ["System"],
43-
response: HealthResponse,
44+
responses: HealthResponse,
4445
},
4546
({ set }) => {
4647
set.headers.test = "test";
@@ -50,19 +51,17 @@ const app = createApp({
5051
};
5152
},
5253
)
53-
5454
.get(
5555
"/api/entries",
5656
{
5757
operationId: "listEntries",
5858
summary: "List all entries",
5959
description: "List all entries in the system",
6060
tags: ["Entries"],
61-
response: Entry.array(),
61+
responses: Entry.array(),
6262
},
6363
() => entries,
6464
)
65-
6665
// curl -X POST -H "Content-Type: application/json" -d '{"id":1,"text":"one"}' http://localhost:3000/api/entries
6766
.post(
6867
"/api/entries",
@@ -78,7 +77,6 @@ const app = createApp({
7877
set.status = Status.Accepted;
7978
},
8079
)
81-
8280
.get(
8381
"/api/entries/:id",
8482
{
@@ -87,22 +85,29 @@ const app = createApp({
8785
description: "Get an entry by ID",
8886
tags: ["Entries"],
8987
params: z.object({ id: z.coerce.number() }),
90-
response: Entry,
88+
responses: {
89+
[Status.Ok]: Entry,
90+
[Status.NotFound]: ErrorResponse,
91+
},
9192
},
92-
({ params }) => {
93+
({ params, status }) => {
9394
const entry = entries.find((entry) => entry.id === params.id);
9495
if (!entry) throw new NotFoundError(undefined, { entryId: params.id });
9596

96-
return entry;
97+
return status(Status.Ok, entry);
9798
},
9899
)
99-
100100
.get(
101101
"/api/csv",
102102
{
103-
response: z.string().meta({ contentType: "text/csv" }),
103+
summary: "Export CSV",
104+
tags: ["Entries"],
105+
responses: z.string().meta({ contentType: "text/csv" }),
106+
},
107+
({ set }) => {
108+
set.headers["Content-Type"] = "text/csv";
109+
return "test";
104110
},
105-
() => "test",
106111
);
107112

108113
console.log(

‎jsr.json‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@
1313
"./errors": "./src/errors.ts",
1414
"./client": "./src/client.ts",
1515
"./testing": "./src/testing.ts",
16-
"./status": "./src/status.ts",
1716
"./adapters/zod-schema-adapter": "./src/adapters/zod-schema-adapter.ts"
1817
}
1918
}

‎src/__tests__/app.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ describe("App", () => {
5353
async ({ respondWith, expectedResponse }) => {
5454
const app = createApp().get(
5555
"/test",
56-
{ response: z.any() },
56+
{ responses: z.any() },
5757
() => respondWith,
5858
);
5959
const client = createTestAppClient(app);

0 commit comments

Comments
 (0)
0