TypeScript typing is an indisputable help in writing safe and readable code. In the case of operating on data that comes from external sources, we can use generators, which will create for us data models and services needed to work with them. It is a requirement to have documentation that accurately describes each contract.
Using generators gives us another advantage (assuming that the documentation is reflected in the actual operation of the API) – it allows us to automatically run the generator and create a Pull Request whenever there is a change in the documentation.
Below I will present two libraries, one based on the OpenAPI standard, allowing us to generate the necessary interfaces and services to work with the API. The other will provide us with the creation of Types based on the GraphQL Schema.
npx openapi-generator-cli generate \ -i PATH_TO_YAML_OR_JSON_INPUT_FILE \ -g typescript-angular \ -o PATH_TO_OUTUP_DICTIONARY \ --additional-properties=ngVersion=X.X.X,supportsES6=true,withInterfaces=true
This library generates everything we need to communicate with APIs – interfaces and a module containing services with methods using Angular HttpClient underneath, returning Observable with a specific type. Additionally, it handles documentation broken into multiple YAML files, as well as recursive types.
npx graphql-codegen init
By calling the above command we will be guided through the configurator. The library will allow us to generate Types based on GraphQL Schema. There are also many plugins available to extend the functionality of the tool. For full documentation visit the project page on GitHub.