|
| 1 | +// Public entry point for the RERUM API v1 server library |
| 2 | +// Only the things exported here are considered a supported, stable |
| 3 | +// API. Internal helpers and modules (controllers, database, routes, |
| 4 | +// etc.) remain private and are not re-exported. Consumers of the |
| 5 | +// package should be able to import from the package root rather than |
| 6 | +// reach into deep paths. |
| 7 | + |
| 8 | +import http from 'http' |
| 9 | +import app from './app.js' |
| 10 | + |
| 11 | +/** |
| 12 | + * Express application instance used throughout the project. Exported |
| 13 | + * primarily for testing or embedding inside another server. |
| 14 | + * |
| 15 | + * ```js |
| 16 | + * import { app } from 'rerum_server' |
| 17 | + * ``` |
| 18 | + */ |
| 19 | +export { app } |
| 20 | + |
| 21 | +/** |
| 22 | + * Default export is the express app largely for backwards compatibility |
| 23 | + * with consumers that do `import app from 'rerum_server'`. |
| 24 | + */ |
| 25 | +export default app |
| 26 | + |
| 27 | +/** |
| 28 | + * Helper that creates an HTTP server for the configured express app. |
| 29 | + * The returned server is **not** listening yet; caller may attach |
| 30 | + * additional listeners or configure timeouts before calling |
| 31 | + * `server.listen(...)`. |
| 32 | + * |
| 33 | + * @param {number|string} [port=process.env.PORT||3001] port to assign to |
| 34 | + * the express app and eventually listen on |
| 35 | + * @returns {import('http').Server} http server instance |
| 36 | + */ |
| 37 | +export function createServer(port = process.env.PORT ?? 3001) { |
| 38 | + app.set('port', port) |
| 39 | + const server = http.createServer(app) |
| 40 | + |
| 41 | + // mirror the configuration from bin/rerum_v1.js so that programmatic |
| 42 | + // users get the same keep-alive behaviour as the CLI entry point. |
| 43 | + server.keepAliveTimeout = 8 * 1000 |
| 44 | + server.headersTimeout = 8.5 * 1000 |
| 45 | + |
| 46 | + return server |
| 47 | +} |
| 48 | + |
| 49 | +/** |
| 50 | + * Convenience function to start the server immediately. Returns the |
| 51 | + * server instance so callers can close it in tests or hook events. |
| 52 | + * |
| 53 | + * @param {number|string} [port] optional port override |
| 54 | + * @returns {import('http').Server} |
| 55 | + */ |
| 56 | +export function start(port) { |
| 57 | + const p = port ?? process.env.PORT ?? 3001 |
| 58 | + const server = createServer(p) |
| 59 | + server.listen(p) |
| 60 | + server.on('listening', () => { |
| 61 | + console.log('LISTENING ON ' + p) |
| 62 | + }) |
| 63 | + return server |
| 64 | +} |
0 commit comments