The application is composed out of two main pillars:
- Vue 3 SPA Frontend application
- Nest.js REST Backend Modular Monolith
In both projects, we use TypeScript everywhere - from components & composables, to services & controllers.
On the backend, we are using Swagger to generate Open API documentation and playground.
This swagger can be configured to not only generate documentation but also the api.json file that contains all Open API schema that later on can be easily used in other tools.
For local development you can do something like this:
const document = SwaggerModule.createDocument(app, config);
writeFileSync('api.json', JSON.stringify(document))
You can read more about this Swagger Module here https://docs.nestjs.com/openapi/introduction
Swagger
This newly generated file will contain all types and available operations for your Backend.
After generating this file, you can then consume it in your frontend application like this:
npx openapi-typescript ./backend/api.json -o ./frontend/schema.d.ts
This will generate a schema file will all the types generated by the Open API specification. Magic πͺ
You can use it in your frontend application like following:
import { components } from '../../schema';
type User = components['schemas']['User']
And you will have full type safety and autocompletion. When I first used it, I instantly felt that this is an amazing feature that could help us a lot.
Summary
This approach is not only about reusability and reducing the lines of code that need to be maintained. It is also about maintaining the contract between Frontend and the Backend. By using one type both in Front and Back, we are making sure that we are not missing any data or passing a wrong parameter name (which is also great for further updating the project types). You can read more about it https://pactflow.io/how-pact-works/?utm_source=ossdocs&utm_campaign=getting_started#slide-1
This is just an example. To make this work fully, you would probably need to also add this schema generation both on frontend and the backend to your CI/CD pipeline so that everything is done automatically and kept in sync :)
In my case, this solution helped a lot. I hope that it will help you as well!