8000 feat: Support model references via a `ref` metadata entry · aklinker1/zeta@e309d7a · GitHub
[go: up one dir, main page]

Skip to content

Commit e309d7a

Browse files
committed
feat: Support model references via a ref metadata entry
1 parent e5ed4ad commit e309d7a

4 files changed

Lines changed: 90 additions & 11 deletions

File tree

‎README.md‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -537,6 +537,27 @@ app.listen(3000);
537537

538538
Without a schema adapter, Zeta will throw an error when trying to access the `/openapi.json` endpoint, but it's not needed if you only want to validate inputs and response bodies.
539539

540+
### Model References
541+
542+
By default, Zeta will not put any models in `components.schemas` nor add `$ref` for those models.
543+
544+
You are in charge of determining which models should be added to `components.schemas` by adding a `ref` meta to the model's schema:
545+
546+
```ts
547+
import { z } from "zod";
548+
549+
const User = z
550+
.object({
551+
id: z.string().uuid(),
552+
email: z.string().email(),
553+
})
554+
.meta({
555+
ref: "User",
556+
});
557+
```
558+
559+
When building your app's spec, Zeta will find these `ref` properties and move the object schemas into `components.schemas`.
560+
540561
## Composing Multiple Apps
541562

542563
By default, an app's context (hooks, decorators) is isolated. To make a child app's context available to its parent, you must explicitly chain `.export()` at the end of its definition. This effectively merges its isolated lifecycle hooks into the parent's.

‎example.ts‎

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,16 +9,26 @@ import { version } from "./package.json" with { type: "json" };
99
import { z } from "zod/v4";
1010
import { zodSchemaAdapter } from "./src/adapters/zod-schema-adapter";
1111

12-
const Entry = z.object({
13-
id: z.number(),
14-
text: z.string(),
15-
});
12+
const Entry = z
13+
.object({
14+
id: z.number(),
15+
text: z.string(),
16+
})
17+
.meta({
18+
ref: "Entry",
19+
});
1620
type Entry = z.infer<typeof Entry>;
1721

18-
const HealthResponse = z.object({
19-
status: z.literal("ok"),
20-
version: z.string().default(version),
21-
});
22+
const Version = z.string().default(version).meta({ ref: "Version" });
23+
24+
const HealthResponse = z
25+
.object({
26+
status: z.literal("ok"),
27+
version: Version,
28+
})
29+
.meta({
30+
ref: "HealthResponse",
31+
});
2232
type HealthResponse = z.infer<typeof HealthResponse>;
2333

2434
const entries: Entry[] = [];

‎src/app.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ export function createApp<TPrefix extends BasePrefix = "">(
116116
console.error("Failed to build OpenAPI docs:", docs.error);
117117
throw docs.error;
118118
}
119-
return docs.docs;
119+
return docs.spec;
120120
});
121121
if (docs.type === "success") {
122122
const scalarHtml = buildScalarHtml(jsonRoute, options);

‎src/open-api.ts‎

Lines changed: 50 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import { ErrorResponseJsonSchema, type ZetaSchema } from "./custom-responses";
88
export function buildOpenApiDocs(
99
options: CreateAppOptions<any> | undefined,
1010
app: App,
11-
): { type: "success"; docs: any } | { type: "error"; error: unknown } {
11+
): { type: "success"; spec: any } | { type: "error"; error: unknown } {
1212
try {
1313
if (!options?.schemaAdapter)
1414
return { type: "error", error: "OpenAPI docs require a schema adapter" };
@@ -85,7 +85,8 @@ export function buildOpenApiDocs(
8585
} as OpenAPI.Operation;
8686
}
8787
}
88-
return { type: "success", docs };
88+
89+
return { type: "success", spec: optimizeSpec(docs) };
8990
} catch (error) {
9091
return { type: "error", error };
9192
}
@@ -184,3 +185,50 @@ function buildResponse(
184185
},
185186
};
186187
}
188+
189+
function optimizeSpec(spec: OpenAPI.Document): OpenAPI.Document {
190+
const optimized = structuredClone(spec);
191+
192+
// Optimizations
193+
addModelRefs(optimized);
194+
195+
return optimized;
196+
}
197+
198+
/**
199+
* Look for `ref` properties from schema metadata and move those models to
200+
* `components.schemas`.
201+
*/
202+
function addModelRefs(spec: any): void {
203+
const recurse = (obj: any): void => {
204+
if (obj == null) return;
205+
if (typeof obj !== "object") return;
206+
207+
// Recursively update array items
208+
if (Array.isArray(obj)) {
209+
for (let i = 0, il = obj.length; i < il; i++) recurse(obj[i]);
210+
return;
211+
}
212+
213+
// Recursively update object properties
214+
const values = Object.values(obj);
215+
for (let i = 0, il = values.length; i < il; i++) recurse(values[i]);
216+
217+
// Move model if it includes a ref
218+
if (typeof obj.ref === "string") {
219+
const ref = obj.ref;
220+
spec.components ??= {};
221+
spec.components.schemas ??= {};
222+
spec.components.schemas[ref] = {
223+
...structuredClone(obj),
224+
// Remove any zeta-only properties OpenAPI doesn't support
225+
ref: undefined,
226+
};
227+
for (const key of Object.keys(obj)) delete obj[key];
228+
obj.$ref = `#/components/schemas/${ref}`;
229+
}
230+
};
231+
232+
// Process the "paths" object
233+
recurse(spec.paths);
234+
}

0 commit comments

Comments
 (0)
0