Skip to content

Commit

Permalink
feat: create server instance http and add close method for graceful s…
Browse files Browse the repository at this point in the history
…hutdown
  • Loading branch information
rsaz committed Nov 27, 2024
1 parent b7bffc5 commit be16011
Showing 1 changed file with 27 additions and 1 deletion.
28 changes: 27 additions & 1 deletion src/adapter-express/application-express.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import express from "express";
import fs from "fs";
import process, { exit } from "process";
import { Server as HTTPServer } from "http";

import {
AppContainer,
Expand Down Expand Up @@ -36,6 +37,7 @@ export class AppExpress extends ApplicationBase implements Server.IWebServer {
private logger: Logger = new Logger();
private console: Console = new Console();
private app: express.Application;
private serverInstance: HTTPServer | null = null;
private port: number;
private environment?: Env.Environment;
private appContainer: AppContainer;
Expand Down Expand Up @@ -200,7 +202,7 @@ export class AppExpress extends ApplicationBase implements Server.IWebServer {
this.app.set("env", this.environment);

this.port = typeof port === "string" ? parseInt(port, 10) : port || 3000;
this.app.listen(this.port, () => {
this.serverInstance = this.app.listen(this.port, () => {
this.console.messageServer(this.port, this.environment, appInfo);

(["SIGTERM", "SIGHUP", "SIGBREAK", "SIGQUIT", "SIGINT"] as Array<NodeJS.Signals>).forEach(
Expand Down Expand Up @@ -345,4 +347,28 @@ export class AppExpress extends ApplicationBase implements Server.IWebServer {
}
return this.app;
}

/**
* Close the server instance.
* @returns A promise that resolves when the server is closed.
* @public API
*/
public close(enableLog: boolean = false): Promise<void> {
return new Promise((resolve, reject) => {
if (this.serverInstance) {
this.serverInstance.close((err?: Error) => {
if (err) {
if (enableLog)
this.logger.error(`Error closing server: ${err.message}`, "adapter-express");
reject(err);
} else {
if (enableLog) this.logger.info("Server closed successfully", "adapter-express");
resolve();
}
});
} else {
resolve();
}
});
}
}

0 comments on commit be16011

Please sign in to comment.