# ServerLoader Class

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

# Overview

abstract class ServerLoader extends PlatformBuilder implements IServerLifecycle {
    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: IHTTPSServerOptions): 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 loadStatics(): 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