From 8ea3a8671af5c4501142d99467bb44bdb56705b8 Mon Sep 17 00:00:00 2001 From: Ilmari <39652086+IlmariKu@users.noreply.github.com> Date: Thu, 5 Dec 2024 12:12:09 +0200 Subject: [PATCH] Example on how to add the openapi-extension to your code --- README.md | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 15186ac..fd95145 100644 --- a/README.md +++ b/README.md @@ -123,7 +123,11 @@ It has three overloads: For this to work, you need to call `extendZodWithOpenApi` once in your project. -Note: This should be done only once in a common-entrypoint file of your project (for example an `index.ts`/`app.ts`). If you're using tree-shaking with Webpack, mark that file as having side-effects. +This should be done only once in a common-entrypoint file of your project (for example an `index.ts`/`app.ts`). If you're using tree-shaking with Webpack, mark that file as having side-effects. + +It can be bit tricky to achieve this in your codebase, because *require* is synchronous and *import* is a async. + +### The basic idea ```ts import { extendZodWithOpenApi } from '@asteasolutions/zod-to-openapi'; @@ -135,6 +139,35 @@ extendZodWithOpenApi(z); z.string().openapi({ description: 'Some string' }); ``` +### Example 1: Calling the openapi-extension using tsx + +``` +//zod-extend.ts + +import { extendZodWithOpenApi } from '@asteasolutions/zod-to-openapi'; +import { z } from 'zod'; + +extendZodWithOpenApi(z); + +// package.json + + "scripts": { + "start": "tsx --import ./zod-extend.ts ./index.ts", +``` + +### Example 2 - require-syntax + +``` +import { extendZodWithOpenApi } from '@asteasolutions/zod-to-openapi'; +import { z } from 'zod'; + +extendZodWithOpenApi(z); + +const { startServer } = require('./server/start'); +startServer(); +``` + + ### The Registry The `OpenAPIRegistry` is a utility that can be used to collect definitions which would later be passed to a `OpenApiGeneratorV3` or `OpenApiGeneratorV31` instance.