This article presents some improvements introduced in version 2 of FoalTS:
- Configuration and type safety
- Configuration and
- Available configuration file formats (JSON, YAML and JS)
- OpenAPI schemas and validation
This article is the part 2 of the series of articles What's new in version 2.0. Part 1 can be found here.
Starting from version 2, a great attention is paid to type safety in the configuration. The
Config.get method allows you specify which type you expect.
In this example, when calling the
get method, the framework will look at the configuration files to retrieve the desired value.
- If the value is not defined, the function returns
- If the value is a number, the function returns it.
- If the value is a string that can be converted to a number (ex:
"1"), the function converts and returns it.
- If the value is not a number and cannot be converted, then the function throws a
ConfigTypeErrorwith the details. Note that the config value is not logged to avoid leaking sensitive information.
If you wish to make the config parameter mandatory, you can do it by using the
getOrThrow method. If no value is found, then a
ConfigNotFound error is thrown.
Supported types are
.env files support#
Version 2 allows you to use different
.env files depending on your environment.
If you configuration is as follows and
production, then the framework will look at
.env.production to retrieve the value and if it does not exist (the file or the value), Foal will look at
JSON and YAML were already supported in version 1. Starting from version 2, JS is also allowed.
In version 1, the names of the environment variables were depending on the names of the configuration keys. For example, when using
Config.get('settings.mongodbUri'), Foal was looking at
Starting from version 2, it is your responsability to choose the environement variable that you want to use (if you use one). This gives more flexibility especially when a Cloud provider defines its own variable names.
Starting from version 1, Foal has allowed you to generate a complete Swagger interface by reading your code. If your application has validation and auth hooks for example, Foal will use them to generate the proper interface.
This is a handy if you want to quickly test and document your API. Then you can customize it in your own way if you wish and complete and override the OpenAPI spec generated by the framework.
In version 2, support of Swagger has been increased to allow you to define OpenAPI schemas and re-use them for validation.
Here is an example.
Stay up to date with the newsletter.