File size: 2,317 Bytes
7ee9dd5 9d865f0 7ee9dd5 0d98acf 7ee9dd5 0d98acf 9d865f0 7ee9dd5 0d98acf 7ee9dd5 0d98acf 7ee9dd5 9d865f0 7ee9dd5 3d1bdb6 7ee9dd5 3d1bdb6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | const path = require('path');
const fs = require('fs');
const Fastify = require('fastify');
const cors = require('@fastify/cors');
const fastifyStatic = require('@fastify/static');
const { CONFIG } = require('./config');
const { routes } = require('./routes');
const { scheduleAll, scheduleGlobalTask } = require('./scheduler');
const { prisma } = require('./db');
const { initAuth } = require('./auth');
async function buildServer() {
const fastify = Fastify({ logger: true });
if (CONFIG.NODE_ENV !== 'production') {
await fastify.register(cors, { origin: true, credentials: true });
}
// Static file path for Docker: /app/web/dist (when __dirname is /app/src)
const staticRoot = path.join(__dirname, '..', 'web', 'dist');
const hasStaticRoot = fs.existsSync(staticRoot);
const indexPath = path.join(staticRoot, 'index.html');
const indexHtml = hasStaticRoot && fs.existsSync(indexPath) ? fs.readFileSync(indexPath) : null;
if (hasStaticRoot) {
await fastify.register(require('@fastify/static'), {
root: staticRoot,
prefix: '/',
decorateReply: false // 避免冲突
});
}
await fastify.register(routes);
if (indexHtml) {
fastify.setNotFoundHandler((req, reply) => {
// For SPA, serve index.html for non-API routes
if (!req.url.startsWith('/api/')) {
return reply.type('text/html').send(indexHtml);
}
reply.code(404).send({ error: 'Not found' });
});
}
// 初始化认证模块
await initAuth(fastify);
await scheduleAll(fastify);
// 加载全局定时任务配置
try {
const scheduleConfig = await prisma.scheduleConfig.findFirst();
if (scheduleConfig) {
await scheduleGlobalTask(scheduleConfig, fastify);
fastify.log.info({ config: scheduleConfig }, 'Global schedule task initialized');
}
} catch (e) {
fastify.log.warn({ err: e.message }, 'Failed to initialize global schedule task');
}
return fastify;
}
async function startServer() {
const app = await buildServer();
await app.listen({ port: CONFIG.PORT, host: '0.0.0.0' });
return app;
}
if (require.main === module) {
startServer().catch((err) => {
// eslint-disable-next-line no-console
console.error(err);
process.exit(1);
});
}
module.exports = { buildServer, startServer };
|