-
Notifications
You must be signed in to change notification settings - Fork 24
Quick Start
Pavel Vostretsov edited this page May 9, 2023
·
3 revisions
This guide will show you how to set up TypeScript.ContractGenerator in your web application
You can find the code for this Quick Start on GitHub here: AspNetCoreExample.Api
First, let's create new AspNet WebApi project using template:
dotnet new webapi --output AspNetCoreExample.Api --framework net7.0
Then navigate to created project and add package reference to TypeScript.ContractGenerator:
dotnet add package SkbKontur.TypeScript.ContractGenerator
For TypeScript.ContractGenerator to know how to generate TypeScript, you need to create folder TypeScriptConfiguration
and two files:
-
TypesProvider
that tells generator what types it should generate, let's start with TypesProvider that returns only existingWeatherForecastController
:
public class TypesProvider : IRootTypesProvider
{
public ITypeInfo[] GetRootTypes()
{
return new[] {TypeInfo.From<WeatherForecastController>()};
}
}
-
CustomGenerator
that tells generator how types should be translated to TypeScript:
public class CustomGenerator : CustomTypeGenerator
{
public CustomGenerator()
{
var controllerBase = TypeInfo.From<ControllerBase>();
WithTypeLocationRule(t => controllerBase.IsAssignableFrom(t), t => $"Api/{t.Name.Replace("Controller", "Api")}")
.WithTypeLocationRule(t => !controllerBase.IsAssignableFrom(t), t => $"DataTypes/{t.Name}")
.WithTypeBuildingContext(t => controllerBase.IsAssignableFrom(t), (u, t) => new ApiControllerTypeBuildingContext(u, t));
}
}
Above we set up several rules for our generator:
- We should types that extend ControllerBase to folder
./Api
, the resulting file forWeatherForecastController
will be./Api/WeatherForecastApi.ts
- We should put everything else to
./DataTypes
folder, for example,WeaterForecast
will be put to./DataTypes/WeatherForecast.ts
- We should use
ApiControllerTypeBuildingContext
to generate api from inheritors ofControllerBase