typescript - moh-hassan/odata2poco GitHub Wiki

The minimal code to generate typescript interfaces use the next script using PowerShell console:

$url="https://services.odata.org/TripPinRESTierService"
o2pgen --url=$url --lang=ts  -f "trip-pin.ts" -v

The options are:

-r <url>   url of the odata server.
--lang=ts  generate typescript code.
-f "trip-pin.ts", the file name to store the generated code.
-v,  to show the generated code on the console.

The generated typescript code:

export namespace Trippin {
	export interface Airline  {
		AirlineCode: string; //Not null, Primary key
		Name: string;
	}

	export interface Airport  {
		Name: string;
		IcaoCode: string; //Not null, Primary key
		IataCode: string;
		Location: AirportLocation;
	}

	export interface City  {
		Name: string;
		CountryRegion: string;
		Region: string;
	}

	export interface Location  {
		Address: string;
		City: City;
	}

	export interface AirportLocation extends Location {
		Loc: number[];
	}

	export interface EventLocation extends Location {
		BuildingInfo: string;
	}

	export interface Person  {
		UserName: string; //Not null, Primary key
		FirstName: string; //Not null
		LastName: string;
		MiddleName: string;
		Gender: PersonGender; //Not null
		Age: number;
		Emails: string[];
		AddressInfo: Location[];
		HomeAddress: Location;
		FavoriteFeature: Feature; //Not null
		Features: Feature[];
		// Friends: Person[]; //navigator
		// BestFriend: Person; //navigator
		// Trips: Trip[]; //navigator
	}

	export interface Employee extends Person {
		Cost: number; //Not null
		// Peers: Person[]; //navigator
	}

	export interface PlanItem  {
		PlanItemId: number; //Not null, Primary key
		ConfirmationCode: string;
		StartsAt: Date; //Not null
		EndsAt: Date; //Not null
		Duration: Date; //Not null
	}

	export interface Event extends PlanItem {
		OccursAt: EventLocation;
		Description: string;
	}

	export enum Feature {
		Feature1=0 ,
		Feature2=1 ,
		Feature3=2 ,
		Feature4=3 
	}

	export interface PublicTransportation extends PlanItem {
		SeatNumber: string;
	}

	export interface Flight extends PublicTransportation {
		FlightNumber: string;
		// Airline: Airline; //navigator
		// From: Airport; //navigator
		// To: Airport; //navigator
	}

	export interface Manager extends Person {
		Budget: number; //Not null
		BossOffice: Location;
		// DirectReports: Person[]; //navigator
	}

	export enum PersonGender {
		Male=0 ,
		Female=1 ,
		Unknown=2 
	}

	export interface Trip  {
		TripId: number; //Not null, Primary key
		ShareId: string; //Not null
		Name: string;
		Budget: number; //Not null
		Description: string;
		Tags: string[];
		StartsAt: Date; //Not null
		EndsAt: Date; //Not null
		// PlanItems: PlanItem[]; //navigator
	}

}

  

The code have trail comments to show not null/ Primary Key/ navigator properties or readonly properties.

The navigation properties are commented. You can uncomment the navigation properties by passing the option -n.


There are other options to configure the typescript code generation. The complete options are:

options for Server Connection:

Table 1 show the description of options in o2pgen tool and the corresponding ODataConnectionString class properties in case you are using c# for developing and generating code as described latter.

Table 1
Option ConnectionString Description
-r, --url ServiceUrl Required. URL of OData feed.
-o, --auth Authenticate (Default: None) Authentication type, allowed values: none, basic, token, oauth2.
-u, --user UserName User name in basic authentication /Or client_id in oauth2.
-p, --password Password password or/token Or access_token /Or client_secret in oauth2.
--domain Domain Domain in Active Directory.
--proxy Proxy Http Proxy in the form: 'server:port'.
-t, --token-endpoint TokenUrl OAuth2 Token Url Endpoint.
--token-params TokenParams OAuth2 Token Parameters with key=value separated by Ampersand '&' formated as: 'client_id=xxx&client_secret=xxx&...', no space is allowed.

Options that control code generation:

Table 2 show the description of options in o2pgen tool and the corresponding PocoSetting in case you use c# for developing and generating code as described latter.

Table 2
Option PocoSetting Description
-f, --filename CodeFilename filename to save generated c# code.
-c, --case NameCase (Default: None) Convert Class Property case. Allowed values are: pas, camel, kebab, snake or none
-n, --navigation AddNavigation Add navigation properties
--lang Lang Type ts for typescript (Default: cs)
--include Include Filter the Entities by FullName, case insensitive. Use space delemeted list of entity names. Name may include the special characters * and ?. The char * represents a string of characters and ? match any single char.
-B, --enable-nullable-reference AddNullableDataType Enable nullable for all reference types by adding ? to type suffix.
-G, --generator-type GeneratorType Generator Type. Allowd values: class or interface
--multi-files MultiFiles Generate multi files.
--full-name UseFullName Use fullname prfixed by namespace as a name for Poco Class.
-v, --verbose Prints C# code to the standard output.

To show all options, display the help screen:

o2pgen --help

Generating multi-file modules.

Use the option: --multi-file

Sample of the generated typescript module:

//flight.ts
import {Airport} from './Airport';
import {AirportLocation} from './AirportLocation';
import {Location} from './Location';
import {City} from './City';
import {Airline} from './Airline';
import {PublicTransportation} from './PublicTransportation';
import {PlanItem} from './PlanItem';


export interface Flight extends PublicTransportation {
	flightNumber: string; //Not null
	from?: Airport; //navigator
	to?: Airport; //navigator
	airline?: Airline; //navigator
}

For Developers

For Developers You can use OData2Poco library to write c# code to generate typescript.

Example: Generate typescript: one single file

var url= "https://services.odata.org/TripPinRESTierService";
 
var connString = new OdataConnectionString
{
    ServiceUrl = url,
    Authenticate = AuthenticationType.None,
};
var setting = new PocoSetting
{
    Lang = Language.TS,
    NameCase = CaseEnum.Camel,
    GeneratorType = GeneratorType.Interface,
    //AddNavigation = true,  //hide navigation properties
    
};
var o2p = new O2P(setting);
var pocostore = await o2p.GenerateTsAsync(connString);
// for single file
var code = pocostore.ToString();
//show code
Console.WriteLine(code);
//save generated code to file trip.ts
pocostore.Save("trip.ts", false);//multifiles=false
 
   

Try it online


Example: Generate typescript: MultiFiles (multi modules)

In this example you generate multi modules (module per file) The generated files can be stored to folder, e.g, 'model' changes to the previous example:

  • set the property MutiFiles=true in PocoSettin
  • Save to folder: pocostore.Save("trip.ts", false);
var url= "https://services.odata.org/TripPinRESTierService";
 
 //for different options for connectin, see Table 1
var connString = new OdataConnectionString
{
    ServiceUrl = url,
    Authenticate = AuthenticationType.None,
};
//for different options for configuration, see Table 2
var setting = new PocoSetting
{
    Lang = Language.TS,
    NameCase = CaseEnum.Camel,
    GeneratorType = GeneratorType.Interface,
    //AddNavigation = true,  //hide navigation properties
	MultiFiles=true
    
};
var o2p = new O2P(setting);
var pocostore = await o2p.GenerateTsAsync(connString);
// for single file
var code = pocostore.ToString();
//show code
Console.WriteLine(code);
//save generated code to folder 'model'
pocostore.Save("model", true); //multifiles=true
   

Try it online

Run the global tool using Msbuild Task

You can auto run dotnet o2pgen from within MsBuild Task and save code in the project folder.

Add the next Msbuild target to your project and modify command parameters as needed. When the property EnableCodeGeneration is set to false, no code is generated. The generated code is saved to file northwind.ts in the folder Model in the root of the project.

<Target Name="GenerateCode" BeforeTargets="Build">
   	<PropertyGroup>
   		<EnableCodeGeneration>true</EnableCodeGeneration>
   	</PropertyGroup>
   	<Exec  Condition="$(EnableCodeGeneration)"
   	  Command="dotnet o2pgen -r http://services.odata.org/V4/Northwind/Northwind.svc/ --lang=ts -f $(MSBuildProjectDirectory)\Model\northwind.ts -B">
   	</Exec>
   </Target>
⚠️ **GitHub.com Fallback** ⚠️