|
| 1 | +import http from 'http' |
| 2 | +import app from './app.js' |
| 3 | + |
| 4 | +/** |
| 5 | + * Express application instance used throughout the project. Exported |
| 6 | + * primarily for testing or embedding inside another server. |
| 7 | + * |
| 8 | + * ```js |
| 9 | + * import { app } from 'rerum_server' |
| 10 | + * ``` |
| 11 | + */ |
| 12 | +export { app } |
| 13 | + |
| 14 | +/** |
| 15 | + * Default export is the express app largely for backwards compatibility |
| 16 | + * with consumers that do `import app from 'rerum_server'`. |
| 17 | + */ |
| 18 | +export default app |
| 19 | + |
| 20 | +/** |
| 21 | + * Helper that creates an HTTP server for the configured express app. |
| 22 | + * The returned server is **not** listening yet; caller may attach |
| 23 | + * additional listeners or configure timeouts before calling |
| 24 | + * `server.listen(...)`. |
| 25 | + * |
| 26 | + * @param {number|string} [port=process.env.PORT||3001] port to assign to |
| 27 | + * the express app and eventually listen on |
| 28 | + * @returns {import('http').Server} http server instance |
| 29 | + */ |
| 30 | +export function createServer(port = process.env.PORT ?? 3001) { |
| 31 | + app.set('port', port) |
| 32 | + const server = http.createServer(app) |
| 33 | + |
| 34 | + server.keepAliveTimeout = 8 * 1000 |
| 35 | + server.headersTimeout = 8.5 * 1000 |
| 36 | + |
| 37 | + return server |
| 38 | +} |
| 39 | + |
| 40 | +/** |
| 41 | + * Convenience function to start the server immediately. Returns the |
| 42 | + * server instance so callers can close it in tests or hook events. |
| 43 | + * |
| 44 | + * @param {number|string} [port] optional port override |
| 45 | + * @returns {import('http').Server} |
| 46 | + */ |
| 47 | +export function start(port) { |
| 48 | + const p = port ?? process.env.PORT ?? 3001 |
| 49 | + const server = createServer(p) |
| 50 | + server.listen(p) |
| 51 | + server.on('listening', () => { |
| 52 | + console.log('LISTENING ON ' + p) |
| 53 | + }) |
| 54 | + return server |
| 55 | +} |
0 commit comments