ServerLoader Class

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

Overview

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

Members

version: string

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.


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;
    }
}

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

Proxy to express set


engine(ext: string, fn: Function): ServerLoader

Proxy to express engine


protected loadSettingsAndInjector(): Promise<;void>;

protected getSettingsService(): ServerSettingsService

start(): Promise<;any>;

Start the express server.


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

Create a new server from settings parameters.


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")
  }
}

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');

addComponents(classes: any | any[], options?: Partial<;IComponentScanned>;): ServerLoader

Add classes to the components list


addControllers(endpoint: string, controllers: any[]): ServerLoader

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

Example

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

new ServerLoader().addControllers('/rest', [MyController])

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. See Versioning Rest API for more information.


protected loadMiddlewares(): Promise<;any>;

Initialize configuration of the express app.


protected setSettings(settings: IServerSettings): void

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,...}
    }
}

readonly expressApp: Express.Application

Return Express Application instance.


readonly injectorService: InjectorService

Return the InjectorService initialized by the server.


readonly injector: InjectorService

Return the injectorService initialized by the server.


readonly httpServer: Http.Server

Return Http.Server instance.


readonly httpsServer: Https.Server

Return Https.Server instance.


static cleanGlobPatterns(files: string | string[], excludes: string[]): string[]