All files server.ts

100% Statements 18/18
100% Branches 16/16
100% Functions 3/3
100% Lines 18/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 661x 1x 1x                                             9x 9x   9x       3x 2x   1x         9x 3x       3x 2x         1x   6x 1x   5x             1x    
import https from "https";
import http from "http";
import http2 from "http2";
 
interface ServerOptions {
  port?: number;
  hostname?: string;
  http2?: boolean;
  https?: {
    allowHTTP1?: boolean;
    key: string;
    cert: string;
  };
}
 
type Handler = (req: http.IncomingMessage | http2.Http2ServerRequest, res: http.OutgoingMessage | http2.Http2ServerResponse) => void;
 
class Server {
  instance: http.Server | https.Server | http2.Http2SecureServer | http2.Http2Server;
 
  private options: ServerOptions;
  private readonly handler: Handler;
 
 
  constructor(handler: Handler, options?: ServerOptions) {
    this.options = options || {};
    this.handler = handler;
 
    this.instance = this.create();
  }
 
  listen(cb?: () => void) {
    if (!this.options.hostname) {
      this.instance.listen(this.options.port || 8000, cb);
    } else {
      this.instance.listen(this.options.port || 8000, this.options.hostname, cb);
    }
  }
 
  private create() {
    if (this.options.https) {
      const httpsSettings = {
        key: this.options.https.key,
        cert: this.options.https.cert,
      };
      if (this.options.http2) {
        return http2.createSecureServer({
          ...httpsSettings,
          allowHTTP1: typeof this.options.https.allowHTTP1 === "boolean" ? this.options.https.allowHTTP1 : true
        }, this.handler);
      } else {
        return https.createServer(httpsSettings, this.handler)
      }
    } else if (this.options.http2) {
      return http2.createServer(this.handler)
    } else {
      return http.createServer(this.handler)
    }
  }
}
 
export {
  ServerOptions,
  Server
}