Skip to content

Commit

Permalink
feat(common): servers.startOnPort() host arg #527
Browse files Browse the repository at this point in the history
Extends the existing functionality of the utility method so that it can
accept a 'host' parameter where callers can
specify if they want to bind to the wildcard
network interface of `0.0.0.0` for example.

The default option of the host argument is
localhost so that we are *secure by default*
even if this method is only used for testing
code, it cannot hurt to be on the safe side.

Fixes #527

Signed-off-by: Peter Somogyvari <peter.somogyvari@accenture.com>
  • Loading branch information
petermetz committed Feb 7, 2021
1 parent f5c2184 commit febc06f
Showing 1 changed file with 11 additions and 10 deletions.
21 changes: 11 additions & 10 deletions packages/cactus-common/src/main/typescript/servers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,14 @@ export class Servers {
* @param server The server object that will be shut down.
*/
public static async shutdown(server: Server | SecureServer): Promise<void> {
const fnTag = `Servers#shutdown()`;
if (!server) {
throw new TypeError(`Servers#shutdown() server was falsy. Need object.`);
throw new TypeError(`${fnTag} server was falsy. Need object.`);
}
return new Promise<void>((resolve, reject) => {
server.close((err: any) => {
server.close((err: Error | undefined) => {
if (err) {
reject(
new Error(
`Servers#shutdown() Failed to shut down server: ${err.stack}`,
),
);
reject(new Error(`${fnTag} Failed to shut down server ${err.stack}`));
} else {
resolve();
}
Expand Down Expand Up @@ -85,10 +82,11 @@ export class Servers {
*/
public static async startOnPreferredPort(
preferredPort?: number,
host = "127.0.0.1",
): Promise<Server> {
if (preferredPort) {
try {
return Servers.startOnPort(preferredPort);
return Servers.startOnPort(preferredPort, host);
} catch (ex) {
// if something else went wrong we still want to just give up
if (!ex.message.includes("EADDRINUSE")) {
Expand All @@ -101,12 +99,15 @@ export class Servers {
}
}

public static async startOnPort(port: number): Promise<Server> {
public static async startOnPort(
port: number,
host = "127.0.0.1",
): Promise<Server> {
const server: Server = await new Promise((resolve, reject) => {
const aServer: Server = createServer();
aServer.once("listening", () => resolve(aServer));
aServer.once("error", (err: Error) => reject(err));
aServer.listen(port, "localhost");
aServer.listen(port, host);
});

return server;
Expand Down

0 comments on commit febc06f

Please sign in to comment.