51 lines
2.3 KiB
JavaScript
51 lines
2.3 KiB
JavaScript
const path = require("node:path");
|
|
const fs = require("node:fs");
|
|
const { createApp } = require("./app");
|
|
const { JsonStore } = require("./store");
|
|
const { PostgresStore } = require("./postgres-store");
|
|
|
|
const host = process.env.HOST || "127.0.0.1";
|
|
const port = Number(process.env.PORT || 3000);
|
|
const identificationPurgeIntervalMs = Number(process.env.IDENTIFICATION_PURGE_INTERVAL_MS || 60 * 60 * 1000);
|
|
const dataDirectory = path.resolve(process.env.DATA_DIR || path.join(__dirname, "..", "data"));
|
|
|
|
async function main() {
|
|
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("PORT 必须是有效端口号");
|
|
const jsonDatabasePath = path.join(dataDirectory, "database.json");
|
|
const hasExistingJsonStore = await fs.promises.access(jsonDatabasePath).then(() => true, () => false);
|
|
if (process.env.NODE_ENV === "production" && !process.env.DATABASE_URL && !hasExistingJsonStore) {
|
|
throw new Error("生产环境必须配置 DATABASE_URL");
|
|
}
|
|
if (process.env.NODE_ENV === "production" && !process.env.DATABASE_URL) {
|
|
console.warn("警告: 正在使用既有 JSON 数据库;请尽快迁移到 PostgreSQL");
|
|
}
|
|
const filesDirectory = path.join(dataDirectory, "files");
|
|
await fs.promises.mkdir(filesDirectory, { recursive: true });
|
|
const store = process.env.DATABASE_URL
|
|
? new PostgresStore(process.env.DATABASE_URL, filesDirectory)
|
|
: new JsonStore(dataDirectory);
|
|
await store.initialize();
|
|
const app = createApp({ store });
|
|
const purgeIdentificationFiles = async () => {
|
|
try {
|
|
const purged = await app.locals.purgeExpiredIdentificationFiles();
|
|
if (purged) console.info(`[retention] purged ${purged} expired identification file(s)`);
|
|
} catch (error) {
|
|
console.error("[retention] identification file purge failed", error);
|
|
}
|
|
};
|
|
await purgeIdentificationFiles();
|
|
const purgeTimer = setInterval(purgeIdentificationFiles, identificationPurgeIntervalMs);
|
|
purgeTimer.unref();
|
|
app.listen(port, host, () => {
|
|
console.log(`ReinLoop server listening on http://${host}:${port}`);
|
|
console.log(`API endpoint: http://${host}:${port}`);
|
|
console.log(`Data directory: ${dataDirectory}`);
|
|
console.log(`Metadata store: ${process.env.DATABASE_URL ? "PostgreSQL" : "local JSON"}`);
|
|
});
|
|
}
|
|
|
|
main().catch((error) => {
|
|
console.error(error.message);
|
|
process.exitCode = 1;
|
|
}); |