Skip to content

Hajime-Suzuki/json-schema-openapi-typescript-code-generation

Repository files navigation

Generate OpenAPI and Typescript types from JSON Schema

Motivation

If you manually:

  • create API docs
  • write validations for incoming body and query params
  • write typescript types

Chances are quite high that they are out of sync. Isn't it great if you can generate all of those from a JSON schema? This is my experiment with JSON schema being a single source of truth, then OpenAPI, Typescript types are generated. Body validations are handled by ajv.


JSON Schema Structure

In schemas folder, there are JSON schema source files. common folder is a place to store files that can be reused across services, and orders folder is for this orders service.


Generating Typescript types

json-schema-to-typescript converts JSON schema files to Typescript types. By running yarn ts, the TS files are created in src/schemas.


Generating OpenAPI files

As described in the @openapi-contrib/json-schema-to-openapi-schema documentation, OpenAPI schemas and JSON schema have discrepancies. It converts JSON schema files to OpenAPI schema files. By running yarn openApi, the OpenAPI schemas are created in api-docs/schemas.

In api-docs/api.yml, converted schemas files are used as references.

From the api.yml, the API documentation is generated by ReDoc


Validations

JSON data can be validated by JSON schema. See src/validations.ts. Referenced schemas must be loaded by addSchema method. Note that JSON schemas are imported not being read by fs.readFile. This is because importing is easier to set up if the app is a serverless function instead of a containerized one.


Automation

When any JSON schema file is changed, the API documentation is also updated and uploaded in S3 bucket through Github Actions.


Todo

  • Check if it's possible to reduce duplicates in generate TS files. (for instance, export type Id = string is everywhere...)
  • Check how to merge all OpenAPI files. It's ideal to centralize all API documentation from different micro-services.
  • Figure out how to effectively share JSON schemas between services. Especially between frontend end and services .

Note

It's a good idea to add generated files to .gitignore, but for now they are in source control for demo purposes.


Developing

  • yarn install to install dependencies
  • yarn downloadCommon to fetch common JSON schema from S3.
  • yarn tsc -w to compile TS files into JS files in watch mode.
  • In a different terminal, run yarn dev to develop the app. Whenever a file in src folder is changed, TS types and OpenAPI Schemas are also re-generated, and the app is also reloaded.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published