# ServerLoader Class deprecated

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

# Overview

abstract class ServerLoader extends PlatformBuilder implements IServerLifecycle {
    static readonly isServerLoader = true;
    version: string;
    constructor(settings?: Partial<TsED.Configuration>);
    /**
     * Return Express Application instance.
     * @returns {core.Express}
     * @deprecated Use this.app.raw
     */
    get expressApp(): Express.Application;
    /**
     * Return the InjectorService initialized by the server.
     * @returns {InjectorService}
     * @deprecated use this.injector
     */
    get injectorService(): InjectorService;
    /**
     * Return Http.Server instance.
     * @returns {Http.Server}
     */
    get httpServer(): Http.Server;
    /**
     * Return Https.Server instance.
     * @returns {Https.Server}
     */
    get httpsServer(): Https.Server;
    static bootstrap(module: any, settings?: Partial<TsED.Configuration>): Promise<ServerLoader>;
    /**
     * Create a new HTTP server with the provided `port`.
     * @returns {ServerLoader}
     * @deprecated Use this.settings.httpPort instead
     */
    createHttpServer(port: string | number): ServerLoader;
    /**
     * Create a new HTTPs server.
     *
     * `options` @@IHTTPSServerOptions@@:
     *
     * key | type | Description
     * ---|---|---
     * port | number | Port number
     * key | string, [Buffer](https://nodejs.org/api/buffer.html#buffer_class_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, [Buffer](https://nodejs.org/api/buffer.html#buffer_class_buffer) | A string, Buffer, array of strings, or array of Buffers containing the certificate key of the server in PEM format. (Required)
     * ca | string, [Buffer](https://nodejs.org/api/buffer.html#buffer_class_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](https://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener).
     *
     * @param options Options to create new HTTPS server.
     * @returns {ServerLoader}
     * @deprecated
     */
    createHttpsServer(options: any): ServerLoader;
    /**
     * This method let you to add a express middleware or a Ts.ED middleware like GlobalAcceptMimes.
     *
     * ```typescript
     * @ServerSettings({
     *    rootDir,
     *    acceptMimes: ['application/json'] // optional
     * })
     * export class Server extends ServerLoader {
     *     $beforeRoutesInit(): void|Promise<any> {
     *         const methodOverride = require('method-override');
     *
     *         this.app
     *             .use(GlobalAcceptMimesMiddleware)
     *             .use(methodOverride());
     *
     *         return null;
     *     }
     * }
     * ```
     * @param args
     * @returns {ServerLoader}
     */
    use(...args: any[]): ServerLoader;
    /**
     * Proxy to express set
     * @param setting
     * @param val
     * @returns {ServerLoader}
     * @deprecated Use this.app.raw.set() instead of
     */
    set(setting: string, val: any): ServerLoader;
    /**
     * Proxy to express engine
     * @param ext
     * @param fn
     * @returns {ServerLoader}
     * @deprecated Use this.app.raw.engine() instead of
     */
    engine(ext: string, fn: (path: string, options: object, callback: (e: any, rendered: string) => void) => void): ServerLoader;
    /**
     * Start the express server.
     * @returns {Promise<any>|Promise}
     */
    start(): Promise<any>;
    /**
     * Run server lifecycle
     */
    runLifecycle(): Promise<void>;
    /**
     * Run listen event and start servers
     */
    listen(): Promise<void>;
    /**
     * Run ready event
     */
    ready(): Promise<void>;
    /**
     * Scan and imports all files matching the pattern. See the document on the [Glob](https://www.npmjs.com/package/glob)
     * pattern for more information.
     *
     * #### Example
     *
     * ```typescript
     * 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.
     *
     * ```typescript
     * const controllerPattern = Path.join(rootDir, 'controllers','**','*.js');
     * ```
     *
     * @param patterns
     * @param endpoint
     * @returns {ServerLoader}
     * @deprecated Will be removed in future
     */
    scan(patterns: string | string[], endpoint?: string): ServerLoader;
    addComponents(classes: any | any[], options?: any): this;
    /**
     * Mount all controllers files that match with `globPattern` ([Glob Pattern](https://www.npmjs.com/package/glob))
     * under the endpoint.
     *
     * ::: tip
     * See [Versioning Rest API](/docs/controllers.md#routing) for more information.
     * :::
     *
     * @param endpoint
     * @param list
     * @returns {ServerLoader}
     * @deprecated use ServerLoader.addControllers instead
     */
    mount(endpoint: string, list: any | string | (any | string)[]): ServerLoader;
    /**
     *
     * @returns {Promise<void>}
     */
    protected loadSettingsAndInjector(): Promise<IRoute[]>;
    /**
     * Initialize configuration of the express app.
     */
    protected loadMiddlewares(routes: IRoute[]): Promise<any>;
    /**
     * Load given routes and add GlobalErrorHandlerMiddleware
     * @param routes
     */
    protected loadRoutes(routes: IRoute[]): Promise<void>;
    protected setSettings(settings: Partial<TsED.Configuration>): void;
    /**
     * Create Server.injector with express application, Http and Https server
     * @param module
     * @param settings
     */
    protected createInjector(module: Type<any> | any, settings: any): 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 {
  $beforeRoutesInit(){
    // add middlewares here
  }
}

// In index.ts
import Server from "./server";

function bootstrap(settings: any) {
  const server = ServerLoader.bootstrap(settings);

  await server.listen()
}

bootstrap();
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

# Members

static readonly isServerLoader = true;

version: string;

get expressApp(): Express.Application;

Return Express Application instance.


get injectorService(): InjectorService;

Return the InjectorService initialized by the server.


get httpServer(): Http.Server;

Return Http.Server instance.


get httpsServer(): Https.Server;

Return Https.Server instance.


static bootstrap(module: any, settings?: Partial<TsED.Configuration>): Promise<ServerLoader>;

createHttpServer(port: string | number): ServerLoader;

Create a new HTTP server with the provided port.


createHttpsServer(options: any): ServerLoader;
Param Type Description
options any Options to create new HTTPS server.

Create a new HTTPs server.

options IHTTPSServerOptions:

key type Description
port number Port number
key 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, Buffer A string, Buffer, array of strings, or array of Buffers containing the certificate key of the server in PEM format. (Required)
ca string, 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 {
    $beforeRoutesInit(): void|Promise<any> {
        const methodOverride = require('method-override');

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

        return null;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

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.


runLifecycle(): Promise<void>;

Run server lifecycle


listen(): Promise<void>;

Run listen event and start servers


ready(): Promise<void>;

Run ready event


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): this;

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<IRoute[]>;

protected loadMiddlewares(routes: IRoute[]): Promise<any>;

Initialize configuration of the express app.


protected loadRoutes(routes: IRoute[]): Promise<void>;

Load given routes and add GlobalErrorHandlerMiddleware


protected setSettings(settings: Partial<TsED.Configuration>): void;

protected createInjector(module: Type<any> | any, settings: any): void;

Create Server.injector with express application, Http and Https server