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.
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.
json-schema-to-typescript converts JSON schema files to Typescript types. By running yarn ts, the TS files are created in src/schemas.
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
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.
When any JSON schema file is changed, the API documentation is also updated and uploaded in S3 bucket through Github Actions.
- Check if it's possible to reduce duplicates in generate TS files. (for instance,
export type Id = stringis 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 .
It's a good idea to add generated files to .gitignore, but for now they are in source control for demo purposes.
yarn installto install dependenciesyarn downloadCommonto fetch common JSON schema from S3.yarn tsc -wto compile TS files into JS files in watch mode.- In a different terminal, run
yarn devto 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.