Skip to content

SwaggerToTypeScriptClientGenerator

Rico Suter edited this page Sep 12, 2016 · 85 revisions

Inherits from ClientGeneratorBase

The following code generates the TypeScript client code and DTO interfaces from a given Swagger specification:

var swaggerSpec = "{}"; 
var service = SwaggerService.FromJson(swaggerSpec);

var settings = new SwaggerToTypeScriptGeneratorSettings
{
	ClassName = "MyClass";
};

var generator = new SwaggerToTypeScriptGenerator(service, settings);
var code = generator.GenerateFile();

Templates

The used template can be set via the Template property of the SwaggerToTypeScriptClientGeneratorSettings class.

JQueryCallbacks

Generates client classes which use JQuery for HTTP handling and simple callbacks for success and error handling.

JQueryPromises

Generates client classes which use JQuery for HTTP handling and JavaScript Promises to handle asynchronicity. Most modern browsers only support JavaScript ES5 which does not provide a native Promise implementation. You can choose from two promise types via the PromiseType setting:

AngularJS

Generates an AngularJS service class which uses the AngularJS http service.

Angular2

The Angular2 template generates an Angular 2 service to access your backend.

Sample

  • Client class name: DataClient
  • TypeScript file name: serviceClients.ts

Usage in an Angular 2 component via dependency injection:

import {HTTP_PROVIDERS} from '@angular/http';
import {DataClient} from 'serviceClients';

@Component({
	providers: [HTTP_PROVIDERS, DataClient]
})
export class MyComponent {
	constructor(public client: DataClient) {
		...
	}

	getData() {
		this.client.getData().subscribe(data => {
			// process data
		}, error => {
			// process error
		});
	}
}

Datetime handling

  • When generating DTO classes instead of interfaces, datetime values are automatically converted into a Date object.
  • Angular 2: In the Angular 2 template, you can pass a JSON.parse reviver function to the client which can convert datetime strings into a Date instance. Sample reviver functions can be found on this StackOverflow question page.

Extended classes and extension code

Settings:

  • TypeScriptGeneratorSettings.ExtendedClasses
  • TypeScriptGeneratorSettings.ExtensionCode

You can extend the generated classes with additional code (like partial classes in C#). Check out the NJsonSchema documentation for more information.

Extension code variables

In the ExtensionCode you can use the {clientClasses} variable which generates a mapping dictionary for all generated client classes. The output will look like:

{"PersonController": PersonController, "CompanyController": CompanyController}

When using the AngularJS template you can use this variable to register all generated client classes as Angular services. To do so, add the following code to your ExtensionCode:

var clientClasses = {clientClasses};
for (var clientClass in clientClasses) {
    if (clientClasses.hasOwnProperty(clientClass)) {
        angular.module('app').service(clientClass, ['$http', clientClasses[clientClass]]);
    } 
}

Extend client classes

It is possible to extend your client classes. With this mechanism, you can add specific security code, caching or additional headers. If you add a client class name to the ExtendedClasses setting, the generator adds the methods transformOptions and transformResult to the generated client class which can then be overridden with own implementations. As an example, look at the following generated client class with extension enabled:

// Sample template: Angular2

class PersonsClientBase {
    ...

    protected transformOptions(options: ) {
        return options;
    }

    protected transformResult(url: string, response: Response, processor: (response: Response) => any) {
        return processor(response); 
    }

    getPersons(...) {
        ...
    
        return this.http.request(url, this.transformOptions({
            ...
        })).map((response) => {
            return this.transformResult(url, (response) => this.processGetPersons(response));
        });
    }

    private processGetPersons(...) {
        ...
    }

    ...
}

In the extension class PersonsClient, you can now transform the options and change the processing of the HTTP results if required. The following code is defined in the ExtensionCode setting:

// Sample template: Angular2

class PersonsClient extends generated.PersonsClientBase {
    protected transformOptions(options: RequestOptionsArgs) {
        // TODO: Change options if required

        options.headers.append("myheader", "myvalue"); 
        return options;
    }

    protected transformResult(url: string, response: Response, processor: (response: Response) => any) {
        // TODO: Return own result or throw exception to change default processing behavior, 
        // or call processor function to run the default processing logic

        console.log("Service call: " + url);
        return processor(response); 
    }
}

The type of the options and response parameters depend on the selected template (i.e. the used framework/library).

Clone this wiki locally