All files / src server.ts

94.29% Statements 66/70
85.71% Branches 30/35
100% Functions 13/13
96.97% Lines 64/66
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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 20012x 12x 12x 12x 12x 12x       12x 12x 12x 12x 12x 12x 12x   12x   12x     12x                         12x             65x 65x 65x     65x 1x                         60x 6x                                           55x 27x   28x                     22x 22x                           188x                     54x 54x     54x 54x   54x 5x 5x   49x 1x       1x   48x     54x 54x                 41x 2x 2x 7x 7x 2x   7x   2x                 60x 54x 54x 54x 54x                 119x 119x 119x 119x 119x 119x 119x   71x          
import express, {Express} from "express";
import cookieParser from "cookie-parser";
import helmet from "helmet";
import "reflect-metadata";
import morgan from "morgan";
import bodyParser from "body-parser";
import * as Http from "http";
import {NextFunction, Request, Response} from "express";
import {ServeStaticOptions} from "serve-static";
import {EVENTS, HTTP_METHODS, TRANSFER_PROTOCOLS} from "./enums";
import {Logger} from "./logger";
import {pubsub} from "./util";
import compression from "compression";
import {injectable} from "inversify";
import responseTime from "response-time";
import {GLOBAL_REQUEST_TIMEOUT, NO_COMPRESS_QUERY_NAME, USE_HELMET, USE_MORGAN} from "./config";
import {ICustomHeader, INodeSpdyConfiguration, ISpdyConfiguration} from "./types";
import * as spdy from "spdy";
import http from "http";
import https from "https";
 
 
const morganLoggingLevels = [
    'Date: [:date[clf]]',
    'IP: :remote-addr',
    'Client-IP: :req[client-ip]',
    'REQ: :method :url',
    'RES: :status :response-time ms',
    'UA: :user-agent',
    'x-correlationId: :req[x-correlationId]',
    'x-agentname: :req[x-agentname]',
    'referer: :req[referer]',
];
 
@injectable()
export class Server {
    app: Express;
    server!: Http.Server | spdy.Server | null;
    private spdyConfiguration: INodeSpdyConfiguration;
 
 
    constructor() {
        this.app = express();
        this.server = null;
        this.addMiddlewares();
 
 
        pubsub.on(EVENTS.ADD_ROUTE, (e: { path: string, method: HTTP_METHODS, handler: (req: Request, res: Response, next: NextFunction) => any }) => {
            this.addRoute(
                e.path,
                e.method,
                e.handler
            );
        });
    }
 
    /**
     * Sets spdy protocol configuration.
     * @param {ISpdyConfiguration} options
     */
    useProtocolOptions(options?: ISpdyConfiguration) {
        if (options) {
            this.spdyConfiguration = {
                cert: options.cert,
                key: options.key,
                passphrase: options.passphrase,
                spdy: {
                    "x-forwarded-for": true,
                    protocols: options.protocols,
                    connection: {
                        windowSize: 1024 * 1024,
                        autoSpdy31: false
                    }
                }
            };
        }
    }
 
    /**
     * Register new middleware to route
     * @param {string | null} path
     * @param {(req: Request, res: Response, next: NextFunction) => any} handler
     */
    addUse(path: string | null, handler: (req: Request, res: Response, next: NextFunction) => any) {
        if (path) {
            this.app.use(path, handler);
        } else {
            this.app.use(handler);
        }
    }
 
    /**
     * Registers static routes
     * @param {string | null} path
     * @param {string} source
     * @param {serveStatic.ServeStaticOptions} staticOptions
     */
    setStatic(path: string | null, source: string, staticOptions?: ServeStaticOptions) {
        Eif (!staticOptions) {
            this.addUse(path, express.static(source));
        } else {
            this.addUse(path, express.static(source, staticOptions));
        }
    }
 
    /**
     * Adds new route
     * @param {string} path
     * @param {HTTP_METHODS} method
     * @param {(req: Request, res: Response, next: NextFunction) => any} handler
     * @param {RequestHandlerParams[]} middlewares
     */
    addRoute(path: string | string[], method: HTTP_METHODS, handler: (req: Request, res: Response, next: NextFunction) => any, middlewares: any[] = []) {
        (this.app as any)[method](path, middlewares, handler);
    }
 
 
    /**
     * Starts server
     * @param {number} port
     * @param {Function} cb
     * @param ipv4
     */
    listen(port: number, cb?: Function, ipv4?: boolean) {
        const args: any = [port];
        Iif (ipv4) {
            args.push('0.0.0.0');
        }
        args.push((e: Error) => {
            cb && cb(e);
        });
        if (this.spdyConfiguration && (this.spdyConfiguration.spdy.protocols.includes(TRANSFER_PROTOCOLS.H2) || this.spdyConfiguration.spdy.protocols.includes(TRANSFER_PROTOCOLS.SPDY))) {
            this.server = spdy.createServer(this.spdyConfiguration, this.app);
            (this.server as http.Server).listen.apply(this.server, args);
        } else {
            if (this.spdyConfiguration && this.spdyConfiguration.cert && this.spdyConfiguration.key) {
                this.server = https.createServer({
                    cert: this.spdyConfiguration.cert,
                    key: this.spdyConfiguration.key
                }, this.app);
                (this.server as https.Server).listen.apply(this.server, args);
            } else {
                this.server = this.app.listen.apply(this.app, args);
            }
        }
        Eif (this.server) {
            this.server.setTimeout(GLOBAL_REQUEST_TIMEOUT);
        }
    }
 
    /**
     * Adds custom headers
     * @param {Array<ICustomHeader>} customHeaders
     */
    addCustomHeaders(customHeaders?: ICustomHeader[]) {
        if (customHeaders) {
            this.addUse(null, (req, res, next) => {
                customHeaders.forEach((customHeader) => {
                    let value: string | undefined = customHeader.value.toString();
                    if (customHeader.isEnv && process.env[value]) {
                        value = process.env[value];
                    }
                    res.header(customHeader.key, value);
                });
                next();
            });
        }
    }
 
    /**
     * Clears instances, stops listening
     */
    close() {
        if (this.server) {
            this.server.close();
            this.server = null;
            this.app = express();
            this.addMiddlewares();
        }
    }
 
    /**
     * Predefined middlewares
     * @returns {boolean}
     */
    private addMiddlewares() {
        this.app.use(responseTime());
        Iif (USE_MORGAN) this.app.use(morgan(morganLoggingLevels.join('||'), {stream: Logger.prototype}));
        Iif (USE_HELMET) this.app.use(helmet());
        this.app.use(bodyParser.urlencoded({extended: true}));
        this.app.use(bodyParser.json());
        this.app.use(cookieParser());
        this.app.use(compression({
            filter(req: any) {
                return !req.query[NO_COMPRESS_QUERY_NAME];
            }
        }));
    }
}