Express Zod API

A Typescript library to help you get an API server up and running with I/O ...

README

Express Zod API


logo

CI
Swagger Validator coverage

downloads
npm release
GitHub Repo stars
License

Start your API server with I/O schema validation and custom middlewares in minutes.

   1. Technologies
   2. Concept
3. Quick start — Fast Track
   1. Installation
   7. Try it
   2. Middlewares
   3. Options
   4. Refinements
   9. Non-object response including file downloads
   11. File uploads

You can find the release notes and migration guides in Changelog.

Why and what is it for


I made this library because of the often repetitive tasks of starting a web server APIs with the need to validate input
data. It integrates and provides the capabilities of popular web server, logger, validation and documenting solutions.
Therefore, many basic tasks can be accomplished faster and easier, in particular:

- You can describe web server routes as a hierarchical object.
- You can keep the endpoint's input and output type declarations right next to its handler.
- All input and output data types are validated, so it ensures you won't have an empty string, null or undefined where
  you expect a number.
- Variables within an endpoint handler have types according to the declared schema, so your IDE and Typescript will
  provide you with necessary hints to focus on bringing your vision to life.
- All of your endpoints can respond in a consistent way.
- The expected endpoint input and response types can be exported to the frontend, so you don't get confused about the
  field names when you implement the client for your API.
- You can generate your API documentation in a Swagger / OpenAPI compatible format.

How it works


Technologies


- Typescript first.
- Web server — Express.js.
- Schema validation — Zod 3.x.
- Logger — Winston.
- Generators:
  - Documentation — OpenAPI 3.x (Swagger Specification).
  - Client side types — Zod-to-TS
- File uploads — Express-FileUpload
  (based on Busboy)

Concept


The API operates object schemas for input and output validation.
The object being validated is the combination of certain request properties.
It is available to the endpoint handler as the input parameter.
Middlewares have access to all request properties, they can provide endpoints with options.
The object returned by the endpoint handler is called output. It goes to the ResultHandler which is
responsible for transmitting consistent responses containing the output or possible error.
Much can be customized to fit your needs.

Dataflow

Quick start


Installation


  1. ``` sh
  2. yarn add express-zod-api
  3. # or
  4. npm install express-zod-api
  5. ```

Add the following option to your tsconfig.json file in order to make it work as expected:

  1. ``` json
  2. {
  3.   "compilerOptions": {
  4.     "strict": true
  5.   }
  6. }
  7. ```

Set up config


  1. ```typescript
  2. import { createConfig } from "express-zod-api";

  3. const config = createConfig({
  4.   server: {
  5.     listen: 8090, // port or socket
  6.   },
  7.   cors: true,
  8.   logger: {
  9.     level: "debug",
  10.     color: true,
  11.   },
  12. });
  13. ```

_See all available options here._

Create an endpoints factory


In the basic case, you can just import and use the default factory:

  1. ```typescript
  2. import { defaultEndpointsFactory } from "express-zod-api";
  3. ```

_In case you need a global middleware, see Middlewares._
_In case you need to customize the response, see Response customization._

Create your first endpoint


  1. ```typescript
  2. import { z } from "express-zod-api";

  3. const helloWorldEndpoint = defaultEndpointsFactory.build({
  4.   method: "get",
  5.   input: z.object({
  6.     // for empty input use z.object({})
  7.     name: z.string().optional(),
  8.   }),
  9.   output: z.object({
  10.     greetings: z.string(),
  11.   }),
  12.   handler: async ({ input: { name }, options, logger }) => {
  13.     logger.debug("Options:", options); // middlewares provide options
  14.     return { greetings: `Hello, ${name || "World"}. Happy coding!` };
  15.   },
  16. });
  17. ```

_In case you want it to handle multiple methods use methods property instead of method._

Set up routing


Connect your endpoint to the /v1/hello route:

  1. ```typescript
  2. import { Routing } from "express-zod-api";

  3. const routing: Routing = {
  4.   v1: {
  5.     hello: helloWorldEndpoint,
  6.   },
  7. };
  8. ```

Start your server


  1. ```typescript
  2. import { createServer } from "express-zod-api";

  3. createServer(config, routing);
  4. ```

You can disable startup logo using startupLogo entry of your config.

Try it


Execute the following command:

  1. ``` sh
  2. curl -L -X GET 'localhost:8090/v1/hello?name=Rick'
  3. ```

You should receive the following response:

  1. ``` json
  2. { "status": "success", "data": { "greetings": "Hello, Rick. Happy coding!" } }
  3. ```

Charming features


Cross-Origin Resource Sharing


You can enable your API for other domains using the corresponding configuration option cors.
It's _not optional_ to draw your attention to making the appropriate decision, however, it's enabled in the
Quick start example above, assuming that in most cases you will want to enable this feature.
See MDN article for more information.

In addition to being a boolean, cors can also be assigned a function that provides custom headers. That function
has several parameters and can be asynchronous.

  1. ```typescript
  2. import { createConfig } from "express-zod-api";

  3. const config = createConfig({
  4.   // ... other options
  5.   cors: ({ defaultHeaders, request, endpoint, logger }) => ({
  6.     ...defaultHeaders,
  7.     "Access-Control-Max-Age": "5000",
  8.   }),
  9. });
  10. ```

Please note: If you only want to send specific headers on requests to a specific endpoint, consider the

Middlewares


Middleware can authenticate using input or request headers, and can provide endpoint handlers with options.
Inputs of middlewares are also available to endpoint handlers within input.

Here is an example on how to provide headers of the request.

  1. ```typescript
  2. import { createMiddleware } from "express-zod-api";

  3. const headersProviderMiddleware = createMiddleware({
  4.   input: z.object({}), // means no inputs
  5.   middleware: async ({ request }) => ({
  6.     headers: request.headers,
  7.   }),
  8. });
  9. ```

By using .addMiddleware() method before .build() you can connect it to the endpoint:

  1. ```typescript
  2. const yourEndpoint = defaultEndpointsFactory
  3.   .addMiddleware(headersProviderMiddleware)
  4.   .build({
  5.     // ...,
  6.     handler: async ({ options }) => {
  7.       // options.headers === request.headers
  8.     },
  9.   });
  10. ```

Here is an example of the authentication middleware, that checks a key from input and token from headers:

  1. ```typescript
  2. import { createMiddleware, createHttpError, z } from "express-zod-api";

  3. const authMiddleware = createMiddleware({
  4.   security: {
  5.     // this information is optional and used for the generated documentation (OpenAPI)
  6.     and: [
  7.       { type: "input", name: "key" },
  8.       { type: "header", name: "token" },
  9.     ],
  10.   },
  11.   input: z.object({
  12.     key: z.string().min(1),
  13.   }),
  14.   middleware: async ({ input: { key }, request, logger }) => {
  15.     logger.debug("Checking the key and token");
  16.     const user = await db.Users.findOne({ key });
  17.     if (!user) {
  18.       throw createHttpError(401, "Invalid key");
  19.     }
  20.     if (request.headers.token !== user.token) {
  21.       throw createHttpError(401, "Invalid token");
  22.     }
  23.     return { user }; // provides endpoints with options.user
  24.   },
  25. });
  26. ```

You can connect the middleware to endpoints factory right away, making it kind of global:

  1. ```typescript
  2. import { defaultEndpointsFactory } from "express-zod-api";

  3. const endpointsFactory = defaultEndpointsFactory.addMiddleware(authMiddleware);
  4. ```

You can connect as many middlewares as you want, they will be executed in order.

Options


In case you'd like to provide your endpoints with options that do not depend on Request, like database connection
instance, consider shorthand method addOptions.

  1. ```typescript
  2. import { defaultEndpointsFactory } from "express-zod-api";

  3. const endpointsFactory = defaultEndpointsFactory.addOptions({
  4.   db: mongoose.connect("mongodb://connection.string"),
  5.   privateKey: fs.readFileSync("private-key.pem", "utf-8"),
  6. });
  7. ```

Refinements


You can implement additional validations within schemas using refinements.
Validation errors are reported in a response with a status code 400.

  1. ```typescript
  2. import { createMiddleware, z } from "express-zod-api";

  3. const nicknameConstraintMiddleware = createMiddleware({
  4.   input: z.object({
  5.     nickname: z
  6.       .string()
  7.       .min(1)
  8.       .refine(
  9.         (nick) => !/^\d.*$/.test(nick),
  10.         "Nickname cannot start with a digit"
  11.       ),
  12.   }),
  13.   // ...,
  14. });
  15. ```

By the way, you can also refine the whole I/O object, for example in case you need a complex validation of its props.

  1. ```typescript
  2. const endpoint = endpointsFactory.build({
  3.   input: z
  4.     .object({
  5.       email: z.string().email().optional(),
  6.       id: z.string().optional(),
  7.       otherThing: z.string().optional(),
  8.     })
  9.     .refine(
  10.       (inputs) => Object.keys(inputs).length >= 1,
  11.       "Please provide at least one property"
  12.     ),
  13.   // ...,
  14. });
  15. ```

Transformations


Since parameters of GET requests come in the form of strings, there is often a need to transform them into numbers or
arrays of numbers.

  1. ```typescript
  2. import { z } from "express-zod-api";

  3. const getUserEndpoint = endpointsFactory.build({
  4.   method: "get",
  5.   input: z.object({
  6.     id: z.string().transform((id) => parseInt(id, 10)),
  7.     ids: z
  8.       .string()
  9.       .transform((ids) => ids.split(",").map((id) => parseInt(id, 10))),
  10.   }),
  11.   output: z.object({
  12.     /* ... */
  13.   }),
  14.   handler: async ({ input: { id, ids }, logger }) => {
  15.     logger.debug("id", id); // type: number
  16.     logger.debug("ids", ids); // type: number[]
  17.   },
  18. });
  19. ```

Dealing with dates


Dates in Javascript are one of the most troublesome entities. In addition, Date cannot be passed directly in JSON
format. Therefore, attempting to return Date from the endpoint handler results in it being converted to an ISO string
in actual response by calling
which in turn calls
It is also impossible to transmit the Date in its original form to your endpoints within JSON. Therefore, there is
confusion with original method z.date() that should not be used within IO schemas of your API.

In order to solve this problem, the library provides two custom methods for dealing with dates: z.dateIn() and
z.dateOut() for using within input and output schemas accordingly.

z.dateIn() is a transforming schema that accepts an ISO string representation of a Date, validates it, and
provides your endpoint handler or middleware with a Date. It supports the following formats:

  1. ```text
  2. 2021-12-31T23:59:59.000Z
  3. 2021-12-31T23:59:59Z
  4. 2021-12-31T23:59:59
  5. 2021-12-31
  6. ```

z.dateOut(), on the contrary, accepts a Date and provides ResultHanlder with a string representation in ISO
format for the response transmission. Consider the following simplified example for better understanding:

  1. ```typescript
  2. import { z, defaultEndpointsFactory } from "express-zod-api";

  3. const updateUserEndpoint = defaultEndpointsFactory.build({
  4.   method: "post",
  5.   input: z.object({
  6.     userId: z.string(),
  7.     birthday: z.dateIn(), // string -> Date
  8.   }),
  9.   output: z.object({
  10.     createdAt: z.dateOut(), // Date -> string
  11.   }),
  12.   handler: async ({ input }) => {
  13.     // input.birthday is Date
  14.     return {
  15.       // transmitted as "2022-01-22T00:00:00.000Z"
  16.       createdAt: new Date("2022-01-22"),
  17.     };
  18.   },
  19. });
  20. ```

Route path params


You can describe the route of the endpoint using parameters:

  1. ```typescript
  2. import { Routing } from "express-zod-api";

  3. const routing: Routing = {
  4.   v1: {
  5.     user: {
  6.       // route path /v1/user/:id, where :id is the path param
  7.       ":id": getUserEndpoint,
  8.       // use the empty string to represent /v1/user if needed:
  9.       // "": listAllUsersEndpoint,
  10.     },
  11.   },
  12. };
  13. ```

You then need to specify these parameters in the endpoint input schema in the usual way:

  1. ```typescript
  2. const getUserEndpoint = endpointsFactory.build({
  3.   method: "get",
  4.   input: z.object({
  5.     // id is the route path param, always string
  6.     id: z.string().transform((value) => parseInt(value, 10)),
  7.     // other inputs (in query):
  8.     withExtendedInformation: z.boolean().optional(),
  9.   }),
  10.   output: z.object({
  11.     /* ... */
  12.   }),
  13.   handler: async ({ input: { id } }) => {
  14.     // id is the route path param, number
  15.   },
  16. });
  17. ```

Response customization


ResultHandler is responsible for transmitting consistent responses containing the endpoint output or an error.
The defaultResultHandler sets the HTTP status code and ensures the following type of the response:

  1. ```typescript
  2. type DefaultResponse<OUT> =
  3.   | {
  4.       // Positive response
  5.       status: "success";
  6.       data: OUT;
  7.     }
  8.   | {
  9.       // or Negative response
  10.       status: "error";
  11.       error: {
  12.         message: string;
  13.       };
  14.     };
  15. ```

You can create your own result handler by using this example as a template:

  1. ```typescript
  2. import {
  3.   createResultHandler,
  4.   createApiResponse,
  5.   IOSchema,
  6.   z,
  7. } from "express-zod-api";

  8. export const yourResultHandler = createResultHandler({
  9.   getPositiveResponse: (output: IOSchema) =>
  10.     createApiResponse(
  11.       z.object({ data: output }),
  12.       "application/json" // optional, or array of mime types
  13.     ),
  14.   getNegativeResponse: () => createApiResponse(z.object({ error: z.string() })),
  15.   handler: ({ error, input, output, request, response, logger }) => {
  16.     // your implementation
  17.   },
  18. });
  19. ```

Then you need to use it as an argument for EndpointsFactory instance creation:

  1. ```typescript
  2. import { EndpointsFactory } from "express-zod-api";

  3. const endpointsFactory = new EndpointsFactory(yourResultHandler);
  4. ```

Please note: ResultHandler must handle any errors and not throw its own. Otherwise, the case will be passed to the
LastResortHandler, which will set the status code to 500 and send the error message as plain text.

Non-object response


Thus, you can configure non-object responses too, for example, to send an image file.

You can find two approaches to EndpointsFactory and ResultHandler implementation
One of them implements file streaming, in this case the endpoint just has to provide the filename.
The response schema generally may be just z.string(), but I made more specific z.file() that also supports
.binary() and .base64() refinements which are reflected in the

  1. ```typescript
  2. const fileStreamingEndpointsFactory = new EndpointsFactory(
  3.   createResultHandler({
  4.     getPositiveResponse: () => createApiResponse(z.file().binary(), "image/*"),
  5.     getNegativeResponse: () => createApiResponse(z.string(), "text/plain"),
  6.     handler: ({ response, error, output }) => {
  7.       if (error) {
  8.         response.status(400).send(error.message);
  9.         return;
  10.       }
  11.       if ("filename" in output) {
  12.         fs.createReadStream(output.filename).pipe(
  13.           response.type(output.filename)
  14.         );
  15.       } else {
  16.         response.status(400).send("Filename is missing");
  17.       }
  18.     },
  19.   })
  20. );
  21. ```

Using native express middlewares


You can connect any native express middleware that can be supplied to express method app.use().
For this purpose the EndpointsFactory provides method addExpressMiddleware() and its alias use().
There are also two optional features available: a provider of options and an error transformer for ResultHandler.
In case the error in middleware is not a HttpError, the ResultHandler will send the status 500.

  1. ```typescript
  2. import { defaultEndpointsFactory, createHttpError } from "express-zod-api";
  3. import cors from "cors";
  4. import { auth } from "express-oauth2-jwt-bearer";

  5. const simpleUsage = defaultEndpointsFactory.addExpressMiddleware(
  6.   cors({ credentials: true })
  7. );

  8. const advancedUsage = defaultEndpointsFactory.use(auth(), {
  9.   provider: (req) => ({ auth: req.auth }), // optional, can be async
  10.   transformer: (err) => createHttpError(401, err.message), // optional
  11. });
  12. ```

File uploads


You can switch the Endpoint to handle requests with the multipart/form-data content type instead of JSON by using
z.upload() schema. Together with a corresponding configuration option, this makes it possible to handle file uploads.
Here is a simplified example:

  1. ```typescript
  2. import { createConfig, z, defaultEndpointsFactory } from "express-zod-api";

  3. const config = createConfig({
  4.   server: {
  5.     upload: true, // <- required
  6.     // ...,
  7.   },
  8. });

  9. const fileUploadEndpoint = defaultEndpointsFactory.build({
  10.   method: "post",
  11.   input: z.object({
  12.     avatar: z.upload(), // <--
  13.   }),
  14.   output: z.object({
  15.     /* ... */
  16.   }),
  17.   handler: async ({ input: { avatar } }) => {
  18.     // avatar: {name, mv(), mimetype, data, size, etc}
  19.     // avatar.truncated is true on failure
  20.   },
  21. });
  22. ```

_You can still send other data and specify additional input parameters, including arrays and objects._

Customizing logger


You can specify your custom Winston logger in config:

  1. ```typescript
  2. import winston from "winston";
  3. import { createConfig } from "express-zod-api";

  4. const logger = winston.createLogger({
  5.   /* ... */
  6. });
  7. const config = createConfig({ logger /* ..., */ });
  8. ```

Connect to your own express app


If you already have your own configured express application, or you find the library settings not enough,
you can connect your routing to the app instead of using createServer().

  1. ```typescript
  2. import express from "express";
  3. import { createConfig, attachRouting } from "express-zod-api";

  4. const app = express();
  5. const config = createConfig({ app /* ..., */ });
  6. const routing = {
  7.   /* ... */
  8. };

  9. const { notFoundHandler, logger } = attachRouting(config, routing);

  10. app.use(notFoundHandler); // optional
  11. app.listen();

  12. logger.info("Glory to science!");
  13. ```

Please note that in this case you probably need to parse request.body, call app.listen() and handle 404
errors yourself. In this regard attachRouting() provides you with notFoundHandler which you can optionally connect
to your custom express app.

Multiple schemas for one route


Thanks to the DependsOnMethod class a route may have multiple Endpoints attached depending on different methods.
It can also be the same Endpoint that handles multiple methods as well.

  1. ```typescript
  2. import { DependsOnMethod } from "express-zod-api";

  3. // the route /v1/user has two Endpoints
  4. // which handle a couple of methods each
  5. const routing: Routing = {
  6.   v1: {
  7.     user: new DependsOnMethod({
  8.       get: yourEndpointA,
  9.       delete: yourEndpointA,
  10.       post: yourEndpointB,
  11.       patch: yourEndpointB,
  12.     }),
  13.   },
  14. };
  15. ```

Serving static files


In case you want your server to serve static files, you can use new ServeStatic() in Routing using the arguments
similar to express.static().
The documentation on these arguments you may find here.

  1. ```typescript
  2. import { Routing, ServeStatic } from "express-zod-api";
  3. import path from "path";

  4. const routing: Routing = {
  5.   // path /public serves static files from ./assets
  6.   public: new ServeStatic(path.join(__dirname, "assets"), {
  7.     dotfiles: "deny",
  8.     index: false,
  9.     redirect: false,
  10.   }),
  11. };
  12. ```

Customizing input sources


You can customize the list of request properties that are combined into input that is being validated and available
to your endpoints and middlewares.

  1. ```typescript
  2. import { createConfig } from "express-zod-api";

  3. createConfig({
  4.   // ...,
  5.   inputSources: {
  6.     // the default value is:
  7.     get: ["query"],
  8.     post: ["body", "files"],
  9.     put: ["body"],
  10.     patch: ["body"],
  11.     delete: ["query", "body"],
  12.   },
  13. });
  14. ```

Enabling compression


it might be a good idea to enable GZIP compression of your API responses. You can achieve and customize it by using the
corresponding configuration option when using the createServer() method.

In order to receive the compressed response the client should include the following header in the request:
Accept-Encoding: gzip, deflate. Only responses with compressible content types are subject to compression. There is
also a default threshold of 1KB that can be configured.

  1. ```typescript
  2. import { createConfig } from "express-zod-api";

  3. const config = createConfig({
  4.   server: {
  5.     // compression: true, or:
  6.     compression: {
  7.       // @see https://www.npmjs.com/package/compression#options
  8.       threshold: "100b",
  9.     },
  10.     // ... other options
  11.   },
  12.   // ... other options
  13. });
  14. ```

Enabling HTTPS


The modern API standard often assumes the use of a secure data transfer protocol, confirmed by a TLS certificate, also
often called an SSL certificate in habit. When using the createServer() method, you can additionally configure and
run the HTTPS server.

  1. ```typescript
  2. import { createConfig, createServer } from "express-zod-api";

  3. const config = createConfig({
  4.   server: {
  5.     listen: 80,
  6.   },
  7.   https: {
  8.     options: {
  9.       cert: fs.readFileSync("fullchain.pem", "utf-8"),
  10.       key: fs.readFileSync("privkey.pem", "utf-8"),
  11.     },
  12.     listen: 443, // port or socket
  13.   },
  14.   // ... cors, logger, etc
  15. });

  16. const { app, httpServer, httpsServer, logger } = createServer(config, routing);
  17. ```

At least you need to specify the port or socket (usually it is 443), certificate and the key, issued by the
certifying authority. For example, you can acquire a free TLS certificate for your API at

Generating a Frontend Client


There is a new way of informing the frontend about the I/O types of your endpoints starting the version 6.1.0.
The new approach offers automatic generation of a client based on routing to a typescript file.
The generated client is flexibly configurable on the frontend side using an implementation function that
directly makes requests to an endpoint using the libraries and methods of your choice.
The client asserts the type of request parameters and response. The feature requires Typescript version 4.1 or higher.

  1. ```typescript
  2. // example client-generator.ts
  3. import fs from "fs";
  4. import { Client } from "express-zod-api";

  5. fs.writeFileSync("./frontend/client.ts", new Client(routing).print(), "utf-8");
  6. ```

  1. ```typescript
  2. // example frontend, simple implementation based on fetch()
  3. import { ExpressZodAPIClient } from "./client.ts";

  4. const client = new ExpressZodAPIClient(async (method, path, params) => {
  5.   const searchParams =
  6.     method === "get" ? `?${new URLSearchParams(params)}` : "";
  7.   const response = await fetch(`https://example.com${path}${searchParams}`, {
  8.     method: method.toUpperCase(),
  9.     headers:
  10.       method === "get" ? undefined : { "Content-Type": "application/json" },
  11.     body: method === "get" ? undefined : JSON.stringify(params),
  12.   });
  13.   return response.json();
  14. });

  15. client.provide("get", "/v1/user/retrieve", { id: "10" });
  16. client.provide("post", "/v1/user/:id", { id: "10" }); // it also substitues path params
  17. ```

Creating a documentation


You can generate the specification of your API and write it to a .yaml file, that can be used as the documentation:

  1. ```typescript
  2. import { OpenAPI } from "express-zod-api";

  3. const yamlString = new OpenAPI({
  4.   routing, // the same routing and config that you use to start the server
  5.   config,
  6.   version: "1.2.3",
  7.   title: "Example API",
  8.   serverUrl: "https://example.com",
  9. }).getSpecAsYaml();
  10. ```

You can add descriptions and examples to your endpoints, their I/O schemas and their properties. It will be included
into the generated documentation of your API. Consider the following example:

  1. ```typescript
  2. import { defaultEndpointsFactory, withMeta } from "express-zod-api";

  3. const exampleEndpoint = defaultEndpointsFactory.build({
  4.   shortDescription: "Retrieves the user.", // <—— this becomes the summary line
  5.   description: "The detailed explanaition on what this endpoint does.",
  6.   input: withMeta(
  7.     z.object({
  8.       id: z.number().describe("the ID of the user"),
  9.     })
  10.   ).example({
  11.     id: 123,
  12.   }),
  13.   // ..., similarly for output and middlewares
  14. });
  15. ```

_See the example of the generated documentation

Tagging the endpoints


When generating documentation, you may find it necessary to classify endpoints into groups. For this, the
possibility of tagging endpoints is provided. In order to achieve the consistency of tags across all endpoints, the
possible tags should be declared in the configuration first and another instantiation approach of the
EndpointsFactory is required. Consider the following example:

  1. ```typescript
  2. import {
  3.   createConfig,
  4.   EndpointsFactory,
  5.   defaultResultHandler,
  6. } from "express-zod-api";

  7. const config = createConfig({
  8.   // ..., use the simple or the advanced syntax:
  9.   tags: {
  10.     users: "Everything about the users",
  11.     files: {
  12.       description: "Everything about the files processing",
  13.       url: "https://example.com",
  14.     },
  15.   },
  16. });

  17. // instead of defaultEndpointsFactory use the following approach:
  18. const taggedEndpointsFactory = new EndpointsFactory({
  19.   resultHandler: defaultResultHandler, // or use your custom one
  20.   config, // <—— supply your config here
  21. });

  22. const exampleEndpoint = taggedEndpointsFactory.build({
  23.   // ...
  24.   tag: "users", // or tags: ["users", "files"]
  25. });
  26. ```

Additional hints


How to test endpoints


The way to test endpoints is to mock the request, response, and logger objects, invoke the execute() method, and
assert the expectations for calls of certain mocked methods. The library provides a special method that makes mocking
easier, it requires jest (and optionally @types/jest) to be installed, so the test might look the following way:

  1. ```typescript
  2. import { testEndpoint } from "express-zod-api";

  3. test("should respond successfully", async () => {
  4.   const { responseMock, loggerMock } = await testEndpoint({
  5.     endpoint: yourEndpoint,
  6.     requestProps: {
  7.       method: "POST", // default: GET
  8.       body: { /* parsed JSON */ },
  9.     },
  10.     // responseProps, configProps, loggerProps
  11.   });
  12.   expect(loggerMock.error).toBeCalledTimes(0);
  13.   expect(responseMock.status).toBeCalledWith(200);
  14.   expect(responseMock.json).toBeCalledWith({
  15.     status: "success",
  16.     data: { ... },
  17.   });
  18. });
  19. ```

_This method is optimized for the defaultResultHandler. With the flexibility to customize, you can add additional
properties as needed._

Excessive properties in endpoint output


The schema validator removes excessive properties by default. However, Typescript
in this case during development. You can achieve this verification by assigning the output schema to a constant and
reusing it in forced type of the output:

  1. ```typescript
  2. import { z } from "express-zod-api";

  3. const output = z.object({
  4.   anything: z.number(),
  5. });

  6. endpointsFactory.build({
  7.   methods,
  8.   input,
  9.   output,
  10.   handler: async (): Promise<z.input<typeof output>> => ({
  11.     anything: 123,
  12.     excessive: "something", // error TS2322, ok!
  13.   }),
  14. });
  15. ```

Your input to my output


Do you have a question or idea?
Your feedback is highly appreciated in Discussions section.

Found a bug?
Please let me know in Issues section.

Found a vulnerability or other security issue?
Please refer to Security policy.