35 lines
1.3 KiB
JavaScript
35 lines
1.3 KiB
JavaScript
import { pathToFileURL } from 'node:url';
|
|
import { readConfig } from './config.mjs';
|
|
import { openStore } from './db.mjs';
|
|
import { buildApp } from './app.mjs';
|
|
|
|
export async function startServer(env = process.env) {
|
|
const config = readConfig(env);
|
|
const store = openStore({ dbPath: config.dbPath });
|
|
let app;
|
|
let stopping;
|
|
const shutdown = () => {
|
|
stopping ??= app.close().catch(() => { process.stderr.write('Server shutdown failed\n'); process.exitCode = 1; });
|
|
return stopping;
|
|
};
|
|
try {
|
|
app = await buildApp({ store, distRoot: config.distRoot, publicOrigin: config.publicOrigin });
|
|
app.addHook('onClose', async () => {
|
|
process.removeListener('SIGTERM', shutdown);
|
|
process.removeListener('SIGINT', shutdown);
|
|
});
|
|
await app.listen({ host: config.host, port: config.port });
|
|
process.once('SIGTERM', shutdown);
|
|
process.once('SIGINT', shutdown);
|
|
} catch (error) {
|
|
if (app) await app.close(); else store.close();
|
|
throw error;
|
|
}
|
|
return app;
|
|
}
|
|
|
|
const entryPath = process.env.pm_exec_path || process.argv[1];
|
|
if (entryPath && import.meta.url === pathToFileURL(entryPath).href) {
|
|
startServer().catch(() => { process.stderr.write('Server startup failed; check configuration, private storage and build\n'); process.exitCode = 1; });
|
|
}
|