• Stars
    star
    188
  • Rank 200,743 (Top 5 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 2 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Zod integration with Fastify

fastify-zod

Why?

fastify is awesome and arguably the best Node http server around.

zod is awesome and arguably the best TypeScript modeling / validation library around.

Unfortunately, fastify and zod don't work together very well. fastify suggests using @sinclair/typebox, which is nice but is nowhere close to zod. This library allows you to use zod as your primary source of truth for models with nice integration with fastify, fastify-swagger and OpenAPI typescript-fetch generator.

Features

  • Define your models using zod in a single place, without redundancy / conflicting sources of truth
  • Use your models in busines logic code and get out of the box type-safety in fastify
  • First-class support for fastify-swagger and openapitools-generator/typescrip-fetch
  • Referential transparency, including for enums
  • Deduplication of structurally equivalent models
  • Internal generated JSON Schemas available for reuse

Setup

  • Install fastify-zod
npm i fastify-zod
  • Define your models using zod
const TodoItemId = z.object({
  id: z.string().uuid(),
});

enum TodoStateEnum {
  Todo = `todo`,
  InProgress = `in progress`,
  Done = `done`,
}

const TodoState = z.nativeEnum(TodoStateEnum);

const TodoItem = TodoItemId.extend({
  label: z.string(),
  dueDate: z.date().optional(),
  state: TodoState,
});

const TodoItems = z.object({
  todoItems: z.array(TodoItem),
});

const TodoItemsGroupedByStatus = z.object({
  todo: z.array(TodoItem),
  inProgress: z.array(TodoItem),
  done: z.array(TodoItem),
});

const models = {
  TodoItemId,
  TodoItem,
  TodoItems,
  TodoItemsGroupedByStatus,
};
  • Register fastify types
import type { FastifyZod } from "fastify-zod";

// Global augmentation, as suggested by
// https://www.fastify.io/docs/latest/Reference/TypeScript/#creating-a-typescript-fastify-plugin
declare module "fastify" {
  interface FastifyInstance {
    readonly zod: FastifyZod<typeof models>;
  }
}

// Local augmentation
// See below for register()
const f = await register(fastify(), { jsonSchemas });
  • Register fastify-zod with optional config for fastify-swagger
import { buildJsonSchemas, register } from "fastify-zod";

const f = fastify();

await register(f, {
  jsonSchemas: buildJsonSchemas(models),
  swaggerOptions: {
    // See https://github.com/fastify/fastify-swagger
  },
  swaggerUiOptions: {
    // See https://github.com/fastify/fastify-swagger-ui
  },
  transformSpec: {}, // optional, see below
});
  • Define fastify routes using simplified syntax and get automatic type inference
f.zod.post(
  `/item`,
  {
    operationId: `postTodoItem`,
    body: `TodoItem`,
    reply: `TodoItems`,
  },
  async ({ body: nextItem }) => {
    /* body is correctly inferred as TodoItem */
    if (state.todoItems.some((prevItem) => prevItem.id === nextItem.id)) {
      throw new BadRequest(`item already exists`);
    }
    state.todoItems = [...state.todoItems, nextItem];
    /* reply is typechecked against TodoItems */
    return state;
  }
);
  • Generate transformed spec with first-class support for downstream openapitools-generator
const transformedSpecJson = await f
  .inject({
    method: `get`,
    url: `/documentation_transformed/json`,
  })
  .then((res) => res.body);

await writeFile(
  join(__dirname, `..`, `..`, `openapi.transformed.json`),
  transformedSpecJson,
  { encoding: `utf-8` }
);
  • Generate OpenAPI Client with openapitools-generator

openapi-generator-cli generate

  • For multiple response types / status codes, use response instead of reply:
f.zod.get(
  `/item/:id`,
  {
    operationId: `getTodoItem`,
    params: `TodoItemId`,
    response: {
      200: `TodoItem`,
      404: `TodoItemNotFoundError`,
    },
  },
  async ({ params: { id } }, reply) => {
    const item = state.todoItems.find((item) => item.id === id);
    if (item) {
      return item;
    }
    reply.code(404);
    return {
      id,
      message: `item not found`,
    };
  }
);
// Define custom messages
const TodoItemId = z.object({
  id: z.string().uuid("this is not a valid id!"),
});

// Then configure fastify
const f = fastify({
  ajv: {
    customOptions: {
      allErrors: true,
    },
  },
  plugins: [require("ajv-errors")],
});

await register(f, {
  jsonSchemas: buildJsonSchemas(models, { errorMessages: true }),
});

API

buildJsonSchemas(models: Models, options: BuildJsonSchemasOptions = {}): BuildJonSchemaResult<typeof models>

Build JSON Schemas and $ref function from Zod models.

The result can be used either with register (recommended, see example in tests) or directly with fastify.addSchema using the $ref function (legacy, see example in tests).

Models

Record mapping model keys to Zod types. Keys will be used to reference models in routes definitions.

Example:

const TodoItem = z.object({
  /* ... */
});
const TodoList = z.object({
  todoItems: z.array(TodoItem),
});

const models = {
  TodoItem,
  TodoList,
};

BuildJsonSchemasOptions = {}

BuildJsonSchemasOptions.$id: string = "Schemas": $id of the generated schema (defaults to "Schemas")
BuildJsonSchemasOptions.target: jsonSchema7|openApi3 = "jsonSchema7": jsonSchema7 (default) or openApi3

Generates either jsonSchema7 or openApi3 schema. See zod-to-json-schema.

BuildJsonSchemasResult<typeof models> = { schemas: JsonSchema[], $ref: $ref<typeof models> }

The result of buildJsonSchemas has 2 components: an array of schemas that can be added directly to fastify using fastify.addSchema, and a $ref function that returns a { $ref: string } object that can be used directly.

If you simply pass the result to register, you won't have to care about this however.

const { schemas, $ref } = buildJsonSchemas(models, { $id: "MySchema" });

for (const schema of schemas) {
  fastify.addSchema(schema);
}

equals($ref("TodoItem"), {
  $ref: "MySchema#/properties/TodoItem",
});

buildJsonSchema($id: string, Type: ZodType) (deprecated)

Shorthand to buildJsonSchema({ [$id]: Type }).schemas[0].

register(f: FastifyInstance, { jsonSchemas, swaggerOptions?: = {} }: RegisterOptions

Add schemas to fastify and decorate instance with zod property to add strongly-typed routes (see fastify.zod below).

RegisterOptions<typeof models>

RegisterOptions<typeof models>.jsonSchema

The result of buildJsonSchemas(models) (see above).

RegisterOptions<typeof models>.swaggerOptions = FastifyDynamicSwaggerOptions & { transformSpec: TransformSpecOptions }

If present, this options will automatically register fastify-swagger in addition to fastify.zod.

Any options will be passed directly to fastify-swagger so you may refer to their documentation.

In addition to fastify-swagger options, you can pass an additional property, transformSpec, to expose a transformed version of the original spec (see below).

await register(f, {
  jsonSchemas: buildJsonSchemas(models),
  swaggerOptions: {
    swagger: {
      info: {
        title: `Fastify Zod Test Server`,
        description: `Test Server for Fastify Zod`,
        version: `0.0.0`,
      },
    },
  },
  swaggerUiOptions: {
    routePrefix: `/swagger`,
    staticCSP: true,
  },
  transformSpec: {
    /* see below */
  },
});
TransformSpecOptions = { cache: boolean = false, routePrefix?: string, options?: TransformOptions }

If this property is present on the swaggerOptions, then in addition to routes added to fastify by fastify-swagger, a transformed version of the spec is also exposed. The transformed version is semantically equivalent but benefits from several improvements, notably first-class support for openapitools-generator-cli (see below).

cache caches the transformed spec. As SpecTransformer can be computationally expensive, this may be useful if used in production. Defaults to false.

routePrefix is the route used to expose the transformed spec, similar to the routePrefix option of fastify-swagger. Defaults to ${swaggerOptions.routePrefix}_transformed. Since swaggerOptions.routePrefix defaults to /documentation, then the default if no routePrefix is provided in either options is /documentation_transformed. The exposed routes are /${routePrefix}/json and /${routePrefix}/yaml for JSON and YAML respectively versions of the transformed spec.

options are options passed to SpecTransformer.transform (see below). By default all transforms are applied.

fastify.zod.(delete|get|head|options|patch|post|put)(url: string, config: RouteConfig, handler)

Add route with strong typing.

Example:

f.zod.put(
  "/:id",
  {
    operationId: "putTodoItem",
    params: "TodoItemId", // this is a key of "models" object above
    body: "TodoItem",
    reply: {
      description: "The updated todo item",
      key: "TodoItem",
    },
  },
  async ({ params: { id }, body: item }) => {
    /* ... */
  }
);

withRefResolver: (options: FastifyDynamicSwaggerOptions) => FastifyDynamicSwaggerOptions

Wraps fastify-swagger options providing a sensible default refResolver function compatible with using the $ref function returned by buildJsonSchemas`.

register automatically uses this under the hood so this is only required if you are using the result of buildJsonSchemas directly without using register.

SpecTransformer(spec: ApiSpec)

SpecTransformer takes an API spec (typically the output of /openapi/json when using fastify-swagger) and applies various transforms. This class is used under the hood by register when swaggerOptions.transformSpec is set so you probably don't need to use it directly.

The transforms should typically be semantically transparent (no semantic difference) but applies some spec-level optimization and most importantly works around the many quirks of the typescript-fetch generator of openapitools-generator-cli.

SpecTransformer is a stateful object that mutates itself internally, but the original spec object is not modified.

Available transforms:

  • rewriteSchemasAbsoluteRefs transform

Transforms $refs relative to a schema to refs relative to the global spec.

Example input:

{
  "components": {
    "schemas": {
      "Schema": {
        "type": "object",
        "properties": {
          "Item": {
            /* ... */
          },
          "Items": {
            "type": "array",
            "items": {
              // "#" refers to "Schema" scope
              "$ref": "#/properties/Item"
            }
          }
        }
      }
    }
  }
}

Output:

{
  "components": {
    "schemas": {
      "Schema": {
        "type": "object",
        "properties": {
          "Item": {
            /* ... */
          },
          "Items": {
            "type": "array",
            "items": {
              // "#" refers to global scope
              "$ref": "#/components/schemas/Schema/properties/Item"
            }
          }
        }
      }
    }
  }
}
  • extractSchemasProperties transform

Extract properties of schemas into new schemas and rewrite all $refs to point to the new schema.

Example input:

{
  "components": {
    "schemas": {
      "Schema": {
        "type": "object",
        "properties": {
          "Item": {
            /* ... */
          },
          "Items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Schema/properties/Item"
            }
          }
        }
      }
    }
  }
}

Output:

{
  "components": {
    "schemas": {
      "Schema": {
        "type": "object",
        "properties": {
          "Item": {
            "$ref": "#/components/schemas/Schema_TodoItem"
          },
          "Items": {
            "$ref": "#/components/schemas/Schema_TodoItems"
          }
        }
      },
      "Schema_TodoItem": {
        /* ... */
      },
      "Schema_TodoItems": {
        "type": "array",
        "items": {
          "$ref": "#/components/schemas/Schema_TodoItem"
        }
      }
    }
  }
}
  • mergeRefs transform

Finds deeply nested structures equivalent to existing schemas and replace them with $refs to this schema. In practice this means deduplication and more importantly, referential equivalence in addition to structrural equivalence. This is especially useful for enums since in TypeScript to equivalent enums are not assignable to each other.

Example input:

{
  "components": {
    "schemas": {
      "TodoItemState": {
        "type": "string",
        "enum": ["todo", "in progress", "done"]
      },
      "TodoItem": {
        "type": "object",
        "properties": {
          "state": {
            "type": "string",
            "enum": ["todo", "in progress", "done"]
          }
        }
      }
    }
  }
}
{
  "mergeRefs": [{
    "$ref": "TodoItemState#"
  }]
}

Output:

{
  "components": {
    "schemas": {
      "TodoItemState": {
        "type": "string",
        "enum": ["todo", "in progress", "done"]
      },
      "TodoItem": {
        "type": "object",
        "properties": {
          "state": {
            "$ref": "#/components/schemas/TodoItemState"
          }
        }
      }
    }
  }
}

In the typical case, you will not create each ref explicitly, but rather use the $ref function provided by buildJsonSchemas:

{
  mergeRefs: [$ref("TodoItemState")];
}
  • deleteUnusedSchemas transform

Delete all schemas that are not referenced anywhere, including in paths. This is useful to remove leftovers of the previous transforms.

Example input:

{
  "components": {
    "schemas": {
      // Schema_TodoItem has been extracted,
      // there are no references to this anymore
      "Schema": {
        "type": "object",
        "properties": {
          "TodoItem": {
            "$ref": "#/components/schemas/Schema_TodoItem"
          }
        }
      },
      "Schema_TodoItem": {
        /* ... */
      }
    }
  },
  "paths": {
    "/item": {
      "get": {
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  // This used to be #/components/Schema/properties/TodoItem
                  // but has been transformed by extractSchemasProperties
                  "$ref": "#/components/schemas/Schema_TodoItem"
                }
              }
            }
          }
        }
      }
    }
  }
}

Output:

{
  "components": {
    "schemas": {
      // "Schema" has been deleted
      "Schema_TodoItem": {
        /* ... */
      }
    }
  },
  "paths": {
    /* ... */
  }
}
  • schemaKeys option

This option controls the behavior of newly created schemas (e.g. during extractSchemasProperties transform).

Available configurations:

  • schemaKeys.removeInitialSchemasPrefix: remove schemaKey prefix of initial schemas to create less verbose schema names, e.g. TodoState instead of MySchema_TodoState

  • schemaKeys.changeCase: change case of generated schema keys. Defaults to preserve. In this case, original schema key and property key prefixes are preserved, and segments are underscore-separated.

In case of schema key conflict, an error will be thrown during transform.

SpecTransformer#transform(options: TransformOptions)

Applies the given transforms.

Default options:

{
  rewriteAbsoluteRefs?: boolean = true,
  extractSchemasProperties?: boolean = true,
  mergeRefs?: { $ref: string }[] = [],
  deleteUnusedSchemas?: boolean = true,
  schemaKeys?: {
    removeInitialSchemasPrefix: boolean = false,
    changeCase: "preserve" | "camelCase" | "PascalCase" | "snake_case" | "param-case" = "preserve"
  } = {}
}

All transforms default to true except mergeRefs that you must explicitly configure.

SpecTransformer#getSpec(): Spec

Return the current state of the spec. This is typically called after transform to use the transformed spec.

Usage with openapitools

Together with fastify-swagger, and SpecTransformer this library supports downstream client code generation using openapitools-generator-cli.

Recommended use is with register and fastify.inject.

For this you need to first generate the spec file, then run openapitools-generator:

const jsonSchemas = buildJsonSchemas(models);

await register(f, {
  jsonSchemas,
  swaggerOptions: {
    openapi: {
      /* ... */
    },
    exposeRoute: true,
    transformSpec: {
      routePrefix: "/openapi_transformed",
      options: {
        mergeRefs: [$ref("TodoItemState")],
      },
    },
  },
});

const spec = await f
  .inject({
    method: "get",
    url: "/openapi_transformed/json",
  })
  .then((spec) => spec.json());

writeFileSync("openapi-spec.json", JSON.stringify(spec), { encoding: "utf-8" });

openapi-generator-cli generate

We recommend running this as part as the build step of your app, see package.json.

Caveats

Unfortunately and despite best efforts by SpecTransformer, the OpenAPI generator has many quirks and limited support for some features. Complex nested arrays are sometimes not validated / parsed correctly, discriminated unions have limited support, etc.

License

MIT License Copyright (c) Elie Rotenberg

More Repositories

1

react-armor

Protect your DOM from third-party tampering.
JavaScript
636
star
2

coding-styles

My coding styles.
398
star
3

react-animate

React animation mixin.
JavaScript
271
star
4

nexus-flux

Streamlined Flux abstract interface suitable for a variety of backends.
JavaScript
241
star
5

remutable

Like Immutable, but actually Mutable with diffs and versions.
JavaScript
222
star
6

react-prepare

Prepare you app state for async server-side rendering and more!
JavaScript
100
star
7

directus-typescript-gen

JavaScript
84
star
8

react-traverse

React Components Magic
JavaScript
70
star
9

nexus-flux-socket.io

socket.io adapter for Nexus Flux, implementing Flux over the Wire.
JavaScript
53
star
10

react-rails-starterkit

Starter repository for React on Rails. Fork it!
JavaScript
47
star
11

typed-assert

A typesafe TS assertion library
TypeScript
47
star
12

react-css

Converts plain CSS into (optionally auto-prefixed) React-style properties map.
JavaScript
35
star
13

es6-starterkit

The future is today!
JavaScript
33
star
14

useless

Useless React hooks
TypeScript
32
star
15

react-query

React Virtual DOM querying made easy.
JavaScript
30
star
16

react-statics-styles

Declarative styles in React components with support for pre- and post-processing.
JavaScript
26
star
17

react-nexus-chat

Demo chat app using React Nexus.
CSS
18
star
18

react-styling-demo

Demos for react-animate, react-css and other React styling demos.
JavaScript
17
star
19

react-defer

React Mixin for dealing with defers/timeouts/intervals/requestAnimationFrame with less boilerplate.
JavaScript
16
star
20

react-nexus-starterkit

React Nexus Starterkit Project. Clone/fork, hack, deploy!
JavaScript
12
star
21

node-async-context

Node Async Context Monitoring & Isolation
JavaScript
8
star
22

immutable-request

Isomorphic cacheable and cancellable HTTP request than return Promise for Immutable.Map.
JavaScript
8
star
23

lifespan

Unifying callbacks removals.
JavaScript
7
star
24

typed-jest-expect

Elegant jest.expect typings for a more civilized age
TypeScript
7
star
25

isomorphic-router

Tiny, lightweight isomorphic router.
JavaScript
6
star
26

gulp-react-statics-styles

Gulp task for react-statics-styles.
JavaScript
5
star
27

tween-interpolate

Extra lightweight generic and CSS values interpolators and tweens.
JavaScript
5
star
28

typed-react-openapi

Idiomatic, strongly typed React OpenAPI integration
TypeScript
5
star
29

hypernode

Ideas and prototypes for Hypernode, a scalable, distributed JS node environment.
JavaScript
4
star
30

react-transform-props

React Component decorator for transforming props
JavaScript
4
star
31

nexus-uplink-simple-server

Nexus Uplink Simple Server (for Node).
JavaScript
4
star
32

react-nexus-app

React Nexus App skeleton.
JavaScript
4
star
33

nexus-uplink-client

Nexus Uplink Client (isomorphic).
JavaScript
4
star
34

algebraic-effects-experiments

Experiments with algebraic effects
JavaScript
3
star
35

react-esi-poc

JavaScript
3
star
36

typecheck-decorator

Runtime arguments validation as ES7 decorators.
JavaScript
3
star
37

virtual

Userland virtual methods and abstract classes for ES6.
JavaScript
3
star
38

typed-result

A liberal reinterpretation of the Result type for TypeScript
TypeScript
3
star
39

lisa-db

TypeScript
2
star
40

react-maybe-state

React Mixin for maybe getting state (defaulting to null).
JavaScript
2
star
41

otter-den

TypeScript
2
star
42

snippets

Snippets of code to copy/paste.
TypeScript
2
star
43

react-ml

JavaScript
2
star
44

http-exceptions

HTTP Exceptions with err codes.
JavaScript
2
star
45

lisa-prototype

TypeScript
2
star
46

react-nexus-todomvc

React Nexus obligatory TodoMVC. (WORK IN PROGRESS)
JavaScript
2
star
47

react-lambda

Higher order and functional utilies for manipulating React components
JavaScript
2
star
48

react-http

Universal HTTP client for use in React applications.
JavaScript
2
star
49

rotenberg.io

My homepage
Lua
1
star
50

RktTools

Wow RktTools addon
Lua
1
star
51

backend-starterkit

Node Koa/postgresql backend starterkit
JavaScript
1
star
52

typed-utilities

Strongly typed general purpose utilities
TypeScript
1
star
53

wow-scripts

Lua
1
star
54

typed-ref

TypeScript
1
star
55

wow-workbench

TypeScript
1
star
56

react-identicon

React Component for Gravatar identicons.
JavaScript
1
star
57

mindstorms-utilities

Utilities for Lego Mindstorms
JavaScript
1
star
58

netlify-cms-toolkit

Tools and utilities for Netlify CMS
TypeScript
1
star
59

nexus-events

Yet Another EventEmitter. Sane callbacks removals.
JavaScript
1
star
60

lodash-next

An extension of lodash for next level js.
JavaScript
1
star
61

remembrall-pi

Python
1
star
62

mindlogger-node

TypeScript
1
star
63

nexus-flux-rest

Nexus Flux backend using plain HTTP requests (REST-like).
JavaScript
1
star
64

workbench

JavaScript
1
star
65

where-did-i-put-it

One button to find them all
TypeScript
1
star
66

node-pg-container

Postgres containers for Node
TypeScript
1
star
67

react-ml-editor

ReactML editor with live preview and suggest-completion.
JavaScript
1
star