Auto-generated TypeScript REST client using Swagger
Description:
In O3, client side relies heavily on REST calls to fetch data from the server. However, most of these calls are constructed manually, by crafting URL strings and params to pass into fetch
or openmrsFetch
. This results in ad-hoc type definitions of these calls, along with the data types that they expect / return, that are sometimes incomplete, duplicated or inconsistent.
The server-side REST module already auto-generates a swagger.json
file specifying the REST endpoints. This file is used for generating Swagger docs (see it on dev3 here). We should be able to use swagger-codegen to also auto-generate TypeScript client and data types for our REST calls, which should elimiate the need to manually construct REST API calls on the client side. . For example, the GET /patient/{uuid}
endpoint can result in the auto-generated code like this:
namespace REST {
function getPatient(uuid: string, v?: string) : Promise<Patient> {
return openmrsFetch(`/patient/${uuid}?v=${v}`);
}
// ...
interface Patient {
uuid: string;
display: string;
// other fields
}
}
Then, to fetch a patient on the client side, and get proper typing for it, we just do this:
const patient = await REST.getPatient(uuid);
Some things to consider:
- The TypeScript generation itself is probably the easy part. The harder part will be to figure out how to set up our build system to publish / import the generated typescript onto the client side. Ideally, our solution should work for all REST endpoints / server modules in the refapp, and also easily adoptable for other server modules that are included in other implemenations.
- We will need to improve the swagger typings for this feature to be more useful. For example the
v=
represenation parameter is defined asenum('default', 'full', 'custom')
, which is not completely correct ascustom
should take in additional string.
Relevance:
This can reduce the boiler-plate code required to define REST calls and their corresponding data types on the client side, improving the overall O3 developer experience.
Skills required:
- knowledge of Swagger docs
- knowledge of server-side resources and endpoints to improve typings
- knowledge of server-side and client-side build / publish process.
Further Reading:
- Documenting REST Resources
- SwaggerSpecificationCreator.java, our custom
swagger.json
generator. - Generated swagger.json file in dev3
- OpenAPI / Swagger specification (v2)