Currently, I am in the process of constructing a WebServer
class with the capability to create either an HTTP or HTTPS express webserver.
The primary objective of the abstract class is to establish some defaults for the express server. The child class that extends it will subsequently add specific settings based on whether the server is configured for http or https.
However, after implementation, I have observed that when utilizing this.app.use(whateveroption)
within the abstract class during server instantiation, the whateveroption
assigned to app.use
is not being set as intended. In the provided example, the API router cannot be accessed (resulting in timeout errors), and both helmet and morgan functionalities are also not properly configured.
Strangely enough, the endpoint at /isalive
appears to be functioning correctly.
Have I overlooked a key aspect here?
CORRECTED : It seems that my error was due to a typo made in this._app.use(express.json())
. The mistake was typing this._app.use(express.json)
instead of this._app.use(express.json())
Abstract Class Definition
abstract class WebServer {
private _app: Express;
private _routers: IWebServerRoute[] = [];
constructor() {
this._applyDefaultToExpressApp();
}
private _applyDefaultToExpressApp() {
this._app = express();
this._app.get("/isalive", (_, res: Response) => res.status(200).json({ status: "I'm alive" })); // <== endpoint functions correctly
const apiRouter = Router();
apiRouter.get("/root", (_, res: Response) => res.status(200).json({ status: "from api root" }));
this._app.use("/api", apiRouter); // <== encountering timeout issue when accessing localhost:5500/api/root
this._app.use(express.json);
this._app.use(
express.urlencoded({
extended: true,
})
);
this._app.use(helmet());
this._app.use(morgan("dev")); // <== no morgan logs appearing in console
}
public get app(): Express {
return this._app;
}
abstract createWebServer(serverOptions: http.ServerOptions | https.ServerOptions): http.Server | https.Server;
}
HTTPWebServer Subclass
class HTTPWebServer extends WebServer {
public server: http.Server;
constructor(httpOptions?: THTTPWebServerOptions | undefined) {
super();
}
public createWebServer(serverOptions?: http.ServerOptions | undefined): http.Server {
if (serverOptions) {
this.server = http.createServer(serverOptions, this.app);
} else {
this.server = http.createServer(this.app);
}
return this.server;
}
}
Sample Usage Scenario
const webServer = new HTTPWebServer();
const server = webServer.createWebServer();
server.listen(port, async () => {
console.log(`server listen to ${port}`);
});