ServerLoader

Module
import { ServerLoader } from "@tsed/common"
Source/packages/common/src/server/components/ServerLoader.ts

Overview

abstract class ServerLoader implements IServerLifecycle {
    version: string;
    constructor();
    readonly injector: InjectorService;
    readonly settings: ServerSettingsService;
    readonly expressApp: Express.Application;
    readonly injectorService: InjectorService;
    readonly httpServer: Http.Server;
    readonly httpsServer: Https.Server;
    createHttpServer(port: string | number): ServerLoader;
    createHttpsServer(options: IHTTPSServerOptions): ServerLoader;
    init(): void;
    use(...args: any[]): ServerLoader;
    set(setting: string, val: any): ServerLoader;
    engine(ext: string, fn: (path: string, options: object, callback: (e: any, rendered: string) =>; void) =>; void): ServerLoader;
    start(): Promise<;any>;;
    scan(patterns: string | string[], endpoint?: string): ServerLoader;
    addComponents(classes: any | any[], options?: any): ServerLoader;
    addControllers(endpoint: string, controllers: any | string | (any | string)[]): void;
    mount(endpoint: string, list: any | string | (any | string)[]): ServerLoader;
    protected loadSettingsAndInjector(): Promise<;void>;;
    protected startServer(http: Http.Server | Https.Server, settings: {
        https: boolean;
        address: string | number;
        port: number;
    }): Promise<;{
        address: string;
        port: number;
        https: boolean;
    }>;;
    protected loadMiddlewares(): Promise<;any>;;
    protected loadRoutes(): Promise<;void>;;
    protected resolve(): Promise<;void>;;
    protected setSettings(settings: IServerSettings): void;
}

Description

ServerLoader provider all method to instantiate an ExpressServer.

It provide some features :

  • Lifecycle hooks,
  • Middleware importation,
  • Scan directory. You can specify controllers and services directory in your project,
// In server.ts
import {ServerLoader, ServerSettings} from "@tsed/common";
import Path = require("path");
@ServerSettings({
   rootDir: Path.resolve(__dirname),
   port: 8000,
   httpsPort: 8080,
   mount: {
     "/rest": "${rootDir}/controllers/**/*.js"
   }
})
export class Server extends ServerLoader {

    $onReady(){
        console.log('Server started...');
    }

    $onServerInitError(err){
        console.error(err);
    }
}

// In app.ts
import Server from "./server";
new Server()
    .start()
    .then(() => console.log('started'))
    .catch(er => console.error(er));

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

Members

version: string

readonly injector: InjectorService

Return the injectorService initialized by the server.


readonly settings: ServerSettingsService

Return the settings configured by the decorator @@ServerSettings@@.

@ServerSettings({
   rootDir: Path.resolve(__dirname),
   port: 8000,
   httpsPort: 8080,
   mount: {
     "/rest": "${rootDir}/controllers/**/*.js"
   }
})
export class Server extends ServerLoader {
    $onInit(){
        console.log(this.settings); // {rootDir, port, httpsPort,...}
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13

readonly expressApp: Express.Application

Return Express Application instance.


readonly injectorService: InjectorService

Return the InjectorService initialized by the server.


readonly httpServer: Http.Server

Return Http.Server instance.


readonly httpsServer: Https.Server

Return Https.Server instance.


createHttpServer(port: string | number): ServerLoader

Create a new HTTP server with the provided port.


createHttpsServer(options: IHTTPSServerOptions): ServerLoader
Param Type Description
options <a href="/api/common/server/interfaces/IHTTPSServerOptions.html"><span class="token">IHTTPSServerOptions</span></a> Options to create new HTTPS server.

Create a new HTTPs server.

options {IHTTPSServerOptions}:

  • port <number>: Port number,
  • key <string> | <string[]> | <Buffer> | <Object[]>: The private key of the server in PEM format. To support multiple keys using different algorithms an array can be provided either as a plain array of key strings or an array of objects in the format {pem: key, passphrase: passphrase}. This option is required for ciphers that make use of private keys.
  • passphrase <string> A string containing the passphrase for the private key or pfx.
  • cert <string> | <string[]> | <Buffer> | <Buffer[]>: A string, Buffer, array of strings, or array of Buffers containing the certificate key of the server in PEM format. (Required)
  • ca <string> | <string[]> | <Buffer> | <Buffer[]>: A string, Buffer, array of strings, or array of Buffers of trusted certificates in PEM format. If this is omitted several well known "root" CAs (like VeriSign) will be used. These are used to authorize connections.

See more info on httpsOptions.


init(): void

Init injector with minimal configuration


use(...args: any[]): ServerLoader

This method let you to add a express middleware or a Ts.ED middleware like GlobalAcceptMimes.

@ServerSettings({
   rootDir,
   acceptMimes: ['application/json'] // optional
})
export class Server extends ServerLoader {
    $onMountingMiddlewares(): void|Promise<any> {
        const methodOverride = require('method-override');

        this.use(GlobalAcceptMimesMiddleware)
            .use(methodOverride());

        // similar to
        this.expressApp.use(methodOverride());

        // but not similar to
        this.expressApp.use(GlobalAcceptMimesMiddleware); // in this case, this middleware will not be added correctly to express.

        return null;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

set(setting: string, val: any): ServerLoader

Proxy to express set


engine(ext: string, fn: (path: string, options: object, callback: (e: any, rendered: string) =>; void) =>; void): ServerLoader

Proxy to express engine


start(): Promise<;any>;

Start the express server.


scan(patterns: string | string[], endpoint?: string): ServerLoader

Scan and imports all files matching the pattern. See the document on the Glob pattern for more information.

Example

import {ServerLoader} from "@tsed/common";
import Path = require("path");

export class Server extends ServerLoader {

   constructor() {
       super();

       let appPath = Path.resolve(__dirname);

       this.scan(appPath + "/controllers/**/**.js")
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13

Theses pattern scan all files in the directories controllers, services recursively.

!> On windows on can have an issue with the Glob pattern and the /. To solve it, build your path pattern with the module Path.

const controllerPattern = Path.join(rootDir, 'controllers','**','*.js');
1

addComponents(classes: any | any[], options?: any): ServerLoader

Add classes to the components list


addControllers(endpoint: string, controllers: any | string | (any | string)[]): void

Add classes decorated by @@Controller()@@ to components container.

Example

@Controller('/ctrl')
class MyController{
}

new ServerLoader().addControllers('/rest', [MyController])
1
2
3
4
5

::: tip If the MyController class isn't decorated, the class will be ignored.

:::


mount(endpoint: string, list: any | string | (any | string)[]): ServerLoader

Mount all controllers files that match with globPattern (Glob Pattern) under the endpoint.

::: tip See Versioning Rest API for more information.

:::


protected loadSettingsAndInjector(): Promise<;void>;

protected startServer(http: Http.Server | Https.Server, settings: {
     https: boolean;
     address: string | number;
     port: number;
 }): Promise<;{
     address: string;
     port: number;
     https: boolean;
 }>;;

Create a new server from settings parameters.


protected loadMiddlewares(): Promise<;any>;

Initialize configuration of the express app.


protected loadRoutes(): Promise<;void>;

protected resolve(): Promise<;void>;

protected setSettings(settings: IServerSettings): void