I'm writing a typical Node.js REST service with endpoints that receive JSON input (as POST bodies) and return JSON responses.
I want these three things:
- JSON schemas defining the shapes of request bodies and response bodies for my endpoints. (Or Swagger files, or anything suitable for defining the contract for clients.)
- TypeScript types/interfaces reflecting the JSON schemas perfectly.
- Runtime validation functions that I can call from my handlers to ensure an object is in the correct shape. (And once an input object has been validated, my TypeScript code should know its interface.)
But I want a single source of truth, to avoid these three components going out of sync. So I only want to hand-maintain one of them (either the JSON Schemas or the TypeScript typings). The other two components should be generated from the hand-written one, and they should not be committed to version control.
I feel like this must be a fairly common set of requirements nowadays, but I can't find much online about it. Perhaps I'm using the wrong search terms to research it. Is there any framework or conventional pattern that addresses this goal, i.e. the goal of defining a JSON API with strict validation of input, standardised schema documentation, and all the convenience of fully typed objects in TypeScript?