I’m building a lot web applications for internal use, my setup is basically ASP.NET Core, React/Angular and Typescript.
I started to find my self duplicating a lot of code from C# into TypeScript types and found this nice little utility https://github.com/pankleks/TypeScriptBuilder that will create TypeScript-models from my code.
This got me thinking about how we communicate with our backend, up until now it’s been a matter of creating “REST-isch” WebApiController’s to expose data, more often than not these endpoints is more or less tailored to a specific view and the actions that can be take from this view. We have never reused the same WebApi for both our own app and any external interaction, the external API would be it’s own thing.
So… after thinking about this I started to test an idea that I got, what if every query and command from the front end could be modeled with a C# “request” and “response”-type that can be shared between frontend and backend? So I made a proof of concept.
My C# code has something called a “FrontendAction” that can be either a command or a query, the FrontendAction must have a “request”-type (incoming information) and a “return”-type (data returned by the action).
Then I’ve created one WebApi-endpoint ActionController with one method: Execute that takes in the request-object, figures out which FrontendActionHandler (C#-class for either a command or request) that should take take of it, execute this handler and returns the “response” object.
This way I can have strongly typed commands / queries in my TypeScript-code that gets genereated (kept in sync) any time I create/change a C#-frontend action. There is almost zero bolierplate (aka. creating WebApiController, methods, actions, and then ajax-code to call the different controllers/methods).
Examples of Queryes:
- GetCustomOverview (parameters: customerId)
- GetCustomerOrders (paramerters: customerId, orderStatus, page)
Examples of Commands:
- SaveCustomer (parameters: CustomerDetailsDto)
- AddOrder (parameters: AddOrderDto)
Have anyone done something similar? How does this approach sound to you?