Spaces:
Sleeping
Sleeping
File size: 2,918 Bytes
b213d9c | 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 79 80 81 82 83 84 85 86 | import Fastify from "fastify";
import cors from "@fastify/cors";
import { Server } from "socket.io";
import { prisma } from "@repo/db";
import * as dotenv from "dotenv";
import * as path from "path";
import fastifyJwt from "@fastify/jwt";
import authRoutes from "./routes/auth";
import questionRoutes from "./routes/questions";
import roomRoutes from "./routes/rooms";
import { questionSetRoutes } from "./routes/questionSets";
import { handleSocketEvents } from "./socket/gameManager";
// βββ Load Environment Variables βββββββββββββββββββββββββββββββββββββββββββββββ
// Priority: apps/api/.env β root .env (fallback for local dev)
dotenv.config({ path: path.resolve(__dirname, "../.env") });
dotenv.config({ path: path.resolve(__dirname, "../../../.env") });
// βββ Validate Required Environment Variables ββββββββββββββββββββββββββββββββββ
const jwtSecret = process.env.JWT_SECRET;
if (!jwtSecret) {
console.error(
"[FATAL] JWT_SECRET environment variable is not set. " +
"Generate one with: openssl rand -base64 32"
);
process.exit(1);
}
const port = parseInt(process.env.PORT || "4000", 10);
// CORS_ORIGIN: comma-separated list of allowed origins for production.
// Example: "https://eduboard.vercel.app,https://www.eduboard.com"
// In development, defaults to localhost:3000.
const corsOrigins: string | string[] | boolean = process.env.CORS_ORIGIN
? process.env.CORS_ORIGIN.split(",").map((o) => o.trim())
: "http://localhost:3000";
// βββ Fastify Instance βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const fastify = Fastify({ logger: true });
// Register Plugins
fastify.register(cors, {
origin: true,
credentials: true,
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
});
fastify.register(fastifyJwt, {
secret: jwtSecret,
});
fastify.get("/health", async () => {
return { status: "ok" };
});
fastify.register(authRoutes, { prefix: "/api/auth" });
fastify.register(questionRoutes, { prefix: "/api/questions" });
fastify.register(roomRoutes, { prefix: "/api/rooms" });
fastify.register(questionSetRoutes, { prefix: "/api/sets" });
const start = async () => {
try {
await fastify.listen({ port, host: "0.0.0.0" });
// Initialize Socket.io attached to Fastify's raw server
const io = new Server(fastify.server, {
cors: {
origin: corsOrigins,
methods: ["GET", "POST"],
},
});
io.on("connection", (socket) => {
handleSocketEvents(io, socket);
});
console.log(`Server and Socket.io started on port ${port}`);
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
};
start();
|