39 lines
823 B
TypeScript
39 lines
823 B
TypeScript
import express from "express";
|
|
|
|
type ServerType = {
|
|
/**
|
|
* The port to listen on
|
|
* @default 3000
|
|
*/
|
|
port: number | string;
|
|
|
|
onLoaded?: () => void;
|
|
};
|
|
|
|
export function createServer({ port = 3000, onLoaded }: ServerType) {
|
|
if (typeof port === "string") {
|
|
port = Number(port);
|
|
if (isNaN(port)) {
|
|
throw new Error("Port must be a number");
|
|
}
|
|
}
|
|
const server = express();
|
|
|
|
// Enable JSON parsing
|
|
server.use(express.json());
|
|
|
|
// Remove the X-Powered-By header
|
|
server.disable("x-powered-by");
|
|
|
|
// Turn on ETag support (for caching)
|
|
server.enable("etag");
|
|
|
|
// Listen on the specified port
|
|
server.listen(port, () => {
|
|
console.log(`Server listening on http://localhost:${port}`);
|
|
onLoaded && onLoaded(); // Call the onLoaded callback if it exists
|
|
});
|
|
|
|
return server;
|
|
}
|