Skip to content

Commit

Permalink
fix(server): better default handling for HOST and PORT
Browse files Browse the repository at this point in the history
  • Loading branch information
jagregory committed May 3, 2020
1 parent df421d7 commit 69b4648
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 20 deletions.
16 changes: 10 additions & 6 deletions src/bin/start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,18 @@ import { createDefaultServer } from "../server";

createDefaultServer()
.then((server) => {
const hostname = process.env.HOST || "localhost";
const port = parseInt(process.env.PORT || "9229", 10);
const hostname = process.env.HOST ?? "localhost";
const port = parseInt(process.env.PORT ?? "9229", 10);
return server.start({ hostname, port });
})
.then((options) => {
console.log(
`Cognito Local running on http://${options.hostname}:${options.port}`
);
.then((httpServer) => {
const address = httpServer.address()!;
const url =
typeof address === "string"
? address
: `${address.address}:${address.port}`;

console.log(`Cognito Local running on http://${url}`);
})
.catch((err) => {
console.error(err);
Expand Down
35 changes: 21 additions & 14 deletions src/server/server.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,25 @@
import bodyParser from "body-parser";
import cors from "cors";
import express from "express";
import * as http from "http";
import { CognitoError, unsupported, UnsupportedError } from "../errors";
import { Router } from "../targets/router";
import PublicKey from "../keys/cognitoLocal.public.json";

export interface ServerOptions {
port?: number;
hostname?: string;
development?: boolean;
port: number;
hostname: string;
development: boolean;
}

export interface Server {
application: any; // eslint-disable-line
start(options?: ServerOptions): Promise<ServerOptions>;
start(options?: Partial<ServerOptions>): Promise<http.Server>;
}

export const createServer = (
router: Router,
options: ServerOptions = {}
options: Partial<ServerOptions> = {}
): Server => {
const app = express();

Expand Down Expand Up @@ -89,20 +90,26 @@ export const createServer = (
return {
application: app,
start(startOptions) {
const actualOptions = {
...options,
...startOptions,
const actualOptions: ServerOptions = {
port: options?.port ?? 9229,
hostname: options?.hostname ?? "localhost",
development: options?.development ?? false,
...options,
...startOptions,
};

return new Promise((resolve, reject) => {
app.listen(actualOptions.port, actualOptions.hostname, (err) => {
if (err) {
reject(err);
} else {
resolve(actualOptions);
const httpServer = app.listen(
actualOptions.port,
actualOptions.hostname,
(err) => {
if (err) {
reject(err);
} else {
resolve(httpServer);
}
}
});
);
});
},
};
Expand Down

0 comments on commit 69b4648

Please sign in to comment.