59 lines
1.8 KiB
JavaScript
59 lines
1.8 KiB
JavaScript
import Fastify from 'fastify';
|
|
import cors from '@fastify/cors';
|
|
import jwt from '@fastify/jwt';
|
|
import fastifyStatic from '@fastify/static';
|
|
import { PrismaClient } from '@prisma/client';
|
|
import { authRoutes } from './routes/auth.js';
|
|
import { logsRoutes } from './routes/logs.js';
|
|
import { reportsRoutes } from './routes/reports.js';
|
|
import path from 'path';
|
|
import { fileURLToPath } from 'url';
|
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
export const prisma = new PrismaClient();
|
|
const fastify = Fastify({
|
|
logger: true,
|
|
});
|
|
await fastify.register(cors, {
|
|
origin: true,
|
|
credentials: true,
|
|
});
|
|
await fastify.register(jwt, {
|
|
secret: process.env.JWT_SECRET || 'default-secret-change-me',
|
|
});
|
|
fastify.decorate('authenticate', async function (request, reply) {
|
|
try {
|
|
await request.jwtVerify();
|
|
}
|
|
catch (err) {
|
|
reply.status(401).send({ error: 'Unauthorized' });
|
|
}
|
|
});
|
|
await fastify.register(authRoutes, { prefix: '/api/auth' });
|
|
await fastify.register(logsRoutes, { prefix: '/api/logs' });
|
|
await fastify.register(reportsRoutes, { prefix: '/api/reports' });
|
|
// Serve static files in production
|
|
if (process.env.NODE_ENV === 'production') {
|
|
await fastify.register(fastifyStatic, {
|
|
root: path.join(__dirname, '../../frontend/dist'),
|
|
prefix: '/',
|
|
});
|
|
fastify.setNotFoundHandler((request, reply) => {
|
|
if (!request.url.startsWith('/api')) {
|
|
return reply.sendFile('index.html');
|
|
}
|
|
reply.status(404).send({ error: 'Not Found' });
|
|
});
|
|
}
|
|
const start = async () => {
|
|
try {
|
|
const port = parseInt(process.env.PORT || '3000', 10);
|
|
await fastify.listen({ port, host: '0.0.0.0' });
|
|
console.log(`Server running on http://localhost:${port}`);
|
|
}
|
|
catch (err) {
|
|
fastify.log.error(err);
|
|
process.exit(1);
|
|
}
|
|
};
|
|
start();
|