{"id":14969164,"url":"https://github.com/fastify/fastify-type-provider-json-schema-to-ts","last_synced_at":"2025-04-04T17:05:11.415Z","repository":{"id":38069261,"uuid":"434447666","full_name":"fastify/fastify-type-provider-json-schema-to-ts","owner":"fastify","description":"A Type Provider for json-schema-to-ts","archived":false,"fork":false,"pushed_at":"2025-03-07T19:11:02.000Z","size":80,"stargazers_count":43,"open_issues_count":5,"forks_count":9,"subscribers_count":13,"default_branch":"main","last_synced_at":"2025-03-28T16:04:47.192Z","etag":null,"topics":["fastify","fastify-library"],"latest_commit_sha":null,"homepage":"https://npmjs.com/package/@fastify/type-provider-json-schema-to-ts","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/fastify.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":"fastify","open_collective":"fastify"}},"created_at":"2021-12-03T02:58:37.000Z","updated_at":"2025-03-14T16:56:19.000Z","dependencies_parsed_at":"2023-02-12T22:15:43.827Z","dependency_job_id":"d4dd94da-cf2c-4445-934f-0ae413d782ce","html_url":"https://github.com/fastify/fastify-type-provider-json-schema-to-ts","commit_stats":{"total_commits":56,"total_committers":15,"mean_commits":"3.7333333333333334","dds":0.625,"last_synced_commit":"93ddf78a72c4b3b1d97262e6c5f656a495e76cf2"},"previous_names":[],"tags_count":12,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-type-provider-json-schema-to-ts","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-type-provider-json-schema-to-ts/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-type-provider-json-schema-to-ts/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-type-provider-json-schema-to-ts/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/fastify","download_url":"https://codeload.github.com/fastify/fastify-type-provider-json-schema-to-ts/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247217172,"owners_count":20903008,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["fastify","fastify-library"],"created_at":"2024-09-24T13:41:15.520Z","updated_at":"2025-04-04T17:05:11.393Z","avatar_url":"https://github.com/fastify.png","language":"TypeScript","funding_links":["https://github.com/sponsors/fastify","https://opencollective.com/fastify"],"categories":[],"sub_categories":[],"readme":"# @fastify/type-provider-json-schema-to-ts\n\n[![CI](https://github.com/fastify/fastify-type-provider-json-schema-to-ts/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fastify/fastify-type-provider-json-schema-to-ts/actions/workflows/ci.yml)\n[![NPM version](https://img.shields.io/npm/v/@fastify/type-provider-json-schema-to-ts.svg?style=flat)](https://www.npmjs.com/package/@fastify/type-provider-json-schema-to-ts)\n[![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard)\n\nA Type Provider for [json-schema-to-ts](https://github.com/ThomasAribart/json-schema-to-ts)\n\n## Install\n\n```bash\nnpm i @fastify/type-provider-json-schema-to-ts\n```\n\n## TypeScript requirements\n\nIt is required to use `TypeScript@4.3` or above with\n[`strict`](https://www.typescriptlang.org/tsconfig#strict)\nmode enabled and\n[`noStrictGenericChecks`](https://www.typescriptlang.org/tsconfig#noStrictGenericChecks)\ndisabled. You may take the following configuration (`tsconfig.json`) as an example:\n\n```json\n{\n  \"compilerOptions\": {\n    \"strict\": true,\n    \"noStrictGenericChecks\": false\n  }\n}\n```\n\n## Plugin definition\n\n\u003e **Note**\n\u003e When using plugin types, `withTypeProvider` is not required to register the plugin.\n\n```ts\nconst plugin: FastifyPluginAsyncJsonSchemaToTs = async function (\n  fastify,\n  _opts\n) {\n  fastify.get(\n    \"/\",\n    {\n      schema: {\n        body: {\n          type: \"object\",\n          properties: {\n            x: { type: \"string\" },\n            y: { type: \"number\" },\n            z: { type: \"boolean\" },\n          },\n          required: [\"x\", \"y\", \"z\"],\n        } as const,\n      },\n    },\n    (req) =\u003e {\n      // The `x`, `y`, and `z` types are automatically inferred\n      const { x, y, z } = req.body;\n    }\n  );\n};\n```\n\n## Setting FromSchema for the validator and serializer\n\nYou can set the `FromSchema` settings for things like [`references`](https://github.com/ThomasAribart/json-schema-to-ts#references) and [`deserialization`](https://github.com/ThomasAribart/json-schema-to-ts#deserialization) for the validation and serialization schema by setting `ValidatorSchemaOptions` and `SerializerSchemaOptions` type parameters.\nYou can use the `deserialize` option in `SerializerSchemaOptions` to allow Date objects in place of date-time strings or other special serialization rules handled by [fast-json-stringify](https://github.com/fastify/fast-json-stringify?tab=readme-ov-file#specific-use-cases).\n\n```ts\nconst userSchema = {\n  type: \"object\",\n  additionalProperties: false,\n  properties: {\n    givenName: { type: \"string\" },\n    familyName: { type: \"string\" },\n  },\n  required: [\"givenName\", \"familyName\"],\n} as const satisfies JSONSchema;\n\nconst sharedSchema = {\n  $id: \"shared-schema\",\n  definitions: {\n    user: userSchema,\n  },\n} as const satisfies JSONSchema;\n\nconst userProfileSchema = {\n  $id: \"userProfile\",\n  type: \"object\",\n  additionalProperties: false,\n  properties: {\n    user: {\n      $ref: \"shared-schema#/definitions/user\",\n    },\n    joinedAt: { type: \"string\", format: \"date-time\" },\n  },\n  required: [\"user\", \"joinedAt\"],\n} as const satisfies JSONSchema\n\n\ntype UserProfile = FromSchema\u003ctypeof userProfileSchema, {\n  references: [typeof sharedSchema]\n  deserialize: [{ pattern: { type: \"string\"; format: \"date-time\" }; output: Date }]\n}\u003e;\n\n// Use JsonSchemaToTsProvider with shared schema references\nconst fastify = Fastify().withTypeProvider\u003c\n  JsonSchemaToTsProvider\u003c{\n    ValidatorSchemaOptions: { references: [typeof sharedSchema] }\n    SerializerSchemaOptions: {\n      references: [typeof userProfileSchema]\n      deserialize: [{ pattern: { type: \"string\"; format: \"date-time\" }; output: Date }]\n    }\n  }\u003e\n\u003e()\n\nfastify.get(\n  \"/profile\",\n  {\n    schema: {\n      body: {\n        type: \"object\",\n        properties: {\n          user: {\n            $ref: \"shared-schema#/definitions/user\",\n          },\n        },\n        required: ['user'],\n      },\n      response: {\n        200: { $ref: \"userProfile#\" },\n      },\n    } as const,\n  },\n  (req, reply) =\u003e {\n    // `givenName` and `familyName` are correctly typed as strings\n    const { givenName, familyName } = req.body.user;\n\n    // Construct a compatible response type\n    const profile: UserProfile = {\n      user: { givenName: \"John\", familyName: \"Doe\" },\n      joinedAt: new Date(), // Returning a Date object\n    };\n\n    // A type error is surfaced if profile doesn't match the serialization schema\n    reply.send(profile)\n  }\n)\n```\n\n## Using References in a Plugin Definition\n\nWhen defining a plugin, shared schema references and deserialization options can also be used with `FastifyPluginAsyncJsonSchemaToTs` and `FastifyPluginCallbackJsonSchemaToTs`.\n\n### Example\n\n```ts\nconst schemaPerson = {\n  $id: \"schema:person\",\n  type: \"object\",\n  additionalProperties: false,\n  properties: {\n    givenName: { type: \"string\" },\n    familyName: { type: \"string\" },\n    joinedAt: { type: \"string\", format: \"date-time\" },\n  },\n  required: [\"givenName\", \"familyName\"],\n} as const satisfies JSONSchema;\n\nconst plugin: FastifyPluginAsyncJsonSchemaToTs\u003c{\n  ValidatorSchemaOptions: { references: [typeof schemaPerson] }\n  SerializerSchemaOptions: {\n    references: [typeof schemaPerson]\n    deserialize: [{ pattern: { type: \"string\"; format: \"date-time\" }; output: Date }]\n  };\n}\u003e = async function (fastify, _opts) {\n  fastify.addSchema(schemaPerson)\n\n  fastify.get(\n    \"/profile\",\n    {\n      schema: {\n        body: {\n          type: \"object\",\n          properties: {\n            user: {\n              $ref: \"schema:person\",\n            },\n          },\n          required: ['user'],\n        },\n        response: {\n          200: { $ref: \"schema:person\" },\n        },\n      }, // as const satisfies JSONSchema is not required thanks to FastifyPluginAsyncJsonSchemaToTs\n    },\n    (req, reply) =\u003e {\n      // `givenName`, `familyName`, and `joinedAt` are correctly typed as strings and validated for format.\n      const { givenName, familyName, joinedAt } = req.body.user;\n\n      // Send a serialized response\n      reply.send({\n        givenName: \"John\",\n        familyName: \"Doe\",\n        // Date objects form DB queries can be returned directly and transformed to string by fast-json-stringify\n        joinedAt: new Date(),\n      })\n    }\n  )\n}\n\nconst callbackPlugin: FastifyPluginCallbackJsonSchemaToTs\u003c{\n  ValidatorSchemaOptions: { references: [typeof schemaPerson] }\n  SerializerSchemaOptions: {\n    references: [typeof schemaPerson]\n    deserialize: [{ pattern: { type: \"string\"; format: \"date-time\" }; output: Date }]\n  };\n}\u003e = (fastify, options, done) =\u003e {\n  // Type check for custom options\n  expectType\u003cstring\u003e(options.optionA)\n\n  // Schema is already added above\n  // fastify.addSchema(schemaPerson);\n\n  fastify.get(\n    \"/callback-profile\",\n    {\n      schema: {\n        body: {\n          type: \"object\",\n          properties: {\n            user: { $ref: \"schema:person\" },\n          },\n          required: [\"user\"],\n        },\n        response: {\n          200: { $ref: \"schema:person\" },\n        },\n      },\n    },\n    (req, reply) =\u003e {\n      const { givenName, familyName, joinedAt } = req.body.user\n\n      reply.send({\n        givenName,\n        familyName,\n        joinedAt: new Date(),\n      });\n    }\n  );\n\n  done()\n};\n```\n\n## License\n\nLicensed under [MIT](./LICENSE).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffastify%2Ffastify-type-provider-json-schema-to-ts","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffastify%2Ffastify-type-provider-json-schema-to-ts","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffastify%2Ffastify-type-provider-json-schema-to-ts/lists"}