(requestHandler)
| 33 | * @constructor |
| 34 | */ |
| 35 | let Server = function (requestHandler) { |
| 36 | let server = http.createServer(function (req, res) { |
| 37 | requestHandler(req, res) |
| 38 | }) |
| 39 | |
| 40 | server.on('connection', function (stream) { |
| 41 | stream.setTimeout(4000) |
| 42 | }) |
| 43 | |
| 44 | /** @typedef {{port: number, address: string, family: string}} */ |
| 45 | let Host // eslint-disable-line |
| 46 | |
| 47 | /** |
| 48 | * Starts the server on the given port. If no port, or 0, is provided, |
| 49 | * the server will be started on a random port. |
| 50 | * @param {number=} opt_port The port to start on. |
| 51 | * @return {!Promise<Host>} A promise that will resolve |
| 52 | * with the server host when it has fully started. |
| 53 | */ |
| 54 | this.start = function (opt_port) { |
| 55 | assert(typeof opt_port !== 'function', 'start invoked with function, not port (mocha callback)?') |
| 56 | const port = opt_port || portprober.findFreePort('127.0.0.1') |
| 57 | return Promise.resolve(port) |
| 58 | .then((port) => { |
| 59 | return promise.checkedNodeCall(server.listen.bind(server, port, '127.0.0.1')) |
| 60 | }) |
| 61 | .then(function () { |
| 62 | return server.address() |
| 63 | }) |
| 64 | } |
| 65 | |
| 66 | /** |
| 67 | * Stops the server. |
| 68 | * @return {!Promise} A promise that will resolve when the |
| 69 | * server has closed all connections. |
| 70 | */ |
| 71 | this.stop = function () { |
| 72 | return new Promise((resolve) => server.close(resolve)) |
| 73 | } |
| 74 | |
| 75 | /** |
| 76 | * @return {Host} This server's host info. |
| 77 | * @throws {Error} If the server is not running. |
| 78 | */ |
| 79 | this.address = function () { |
| 80 | const addr = server.address() |
| 81 | if (!addr) { |
| 82 | throw Error('There server is not running!') |
| 83 | } |
| 84 | return addr |
| 85 | } |
| 86 | |
| 87 | /** |
| 88 | * return {string} The host:port of this server. |
| 89 | * @throws {Error} If the server is not running. |
| 90 | */ |
| 91 | this.host = function () { |
| 92 | return net.getLoopbackAddress() + ':' + this.address().port |
nothing calls this directly
no test coverage detected