DRY routes between C# and Angular

I have an Angular 5 app talking to a C# api. Having magic strings for the end-points in both the TypeScript and the C# route attributes seems fragile to me:

I wanted a single source of urls, so the first step was to create a C# class of constants and use them in the controller.

Manually typing an equivalent TypeScript class may make the code a fraction less fragile, but it would still be writing the same code twice. Ideally the Angular app would be able to access the C# constants, but there's no direct way. I've been a big fan of code generation over the years, using NimbleText, CodeSmith, Resharper templates and T4. My plan was to generate a TypeScript class from the C# class. I plumped for T4. This uses reflection on the class to get a list of the class's constants containing the urls. It loops round them, checking for parameters, e.g. {kittenId}. If there are any, the template generates a function that accepts the parameters and returns the formatted string. If there are no paramters, then a property is generated instead. The output of this template is included in the Angular app, and is accessible from the rest of the code.

A much less fragile way of linking front- and back-ends through code generation.

7 March 2018