Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
189 lines (160 loc) · 5.45 KB
/
Copy pathserver.js
File metadata and controls
189 lines (160 loc) · 5.45 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
import express from "express";
import dotenv from "dotenv";
import cors from "cors";
import helmet from "helmet";
import pool from "./src/config/db.js";
// Routes Imports
import defaultRouter from "./src/defaultRoute.js";
import productRouter from "./src/modules/Products/productRoutes.js";
import productMediaRoutes from "./src/modules/ProductMedia/productMediaRoutes.js";
import authRoutes from "./src/modules/AuthSystem/authRoutes.js";
import authAdminRoutes from "./src/modules/AuthAdmin/authAdminRoutes.js";
import inventoryManagementRoutes from "./src/modules/InventoryManagement/inventoryRoutes.js";
import inventoryMovementsRoutes from "./src/modules/InventoryMovements/inventoryMovementRoutes.js";
import cartSystemRoutes from "./src/modules/cartSystem/cartRoutes.js";
// Tables Imports
import { productTable } from "./src/db/productTable.sql.js";
import { userTable } from "./src/db/userTable.sql.js";
import { productMediaTable } from "./src/db/productMediaTable.sql.js";
import { inventoryTable } from "./src/db/inventoryTable.sql.js";
import { inventoryMovementTable } from "./src/db/inventoryMovementTable.sql.js";
import { cartTable } from "./src/db/cartTable.sql.js";
import { cartItemTable } from "./src/db/cartItemTable.sql.js";
// Swagger Imports
import swaggerUi from "swagger-ui-express";
import swaggerSpec from "./src/config/swagger.js";
// Redis Imports
import redisClient from "./src/config/redis.js";
import redisRouter from "./src/modules/RedisAdminStats/redisRoutes.js";
// Redis Warm Cache Routes
import cacheWarmRoutes from "./src/modules/RedisAdminStats/cacheWarmRoutes.js";
// Redis Stats Routes
import redisStatsRoutes from "./src/modules/RedisAdminStats/redisStatsRoutes.js";
// Dev Scripts
import { seedAminUser } from "./src/seed/admin.seed.js";
// Instances Creation
dotenv.config();
const app = express();
const PORT = process.env.BACKEND_PORT || 8000;
// Default Middlewares
app.use(
cors({
origin: (origin, callback) => {
// Allow requests with no origin (like Postman)
if (!origin) return callback(null, true);
// Allow localhost (dev)
if (origin.includes("localhost")) {
return callback(null, true);
}
// Allow ALL vercel deployments
if (origin.includes("vercel.app")) {
return callback(null, true);
}
// Block everything else
return callback(new Error("Not allowed by CORS"));
},
methods: ["GET", "POST", "PUT", "DELETE"],
credentials: true,
allowedHeaders: ["Content-Type", "Authorization"],
}),
);
app.use(express.json());
// Logger Middleware
app.use((req, res, next) => {
res.on("finish", () => {
const timeStamp = new Date().toISOString();
console.log(`[${timeStamp}] ${req.method} ${req.url} ${res.statusCode}`);
});
next();
});
// Security Middleware
app.use(helmet());
// Router Usage
app.use("/api/v1/RedisImplementation/health", defaultRouter);
app.use("/api/v1/RedisImplementation/auth", authRoutes);
app.use("/api/v1/RedisImplementation/auth/admin", authAdminRoutes);
app.use("/api/v1/RedisImplementation/products", productRouter);
app.use("/api/v1/RedisImplementation/redis", redisRouter);
app.use("/api/v1/RedisImplementation/cache", cacheWarmRoutes);
app.use("/api/v1/RedisImplementation/redis", redisStatsRoutes);
app.use("/api/v1/RedisImplementation/product-media", productMediaRoutes);
app.use("/api/v1/RedisImplementation/inventory", inventoryManagementRoutes);
app.use("/api/v1/RedisImplementation/cart", cartSystemRoutes);
app.use(
"/api/v1/RedisImplementation/inventory-movements",
inventoryMovementsRoutes,
);
app.use(
"/api-docs/RedisImplementation",
swaggerUi.serve,
swaggerUi.setup(swaggerSpec),
);
// 404 Handler
app.use((req, res) => {
res.status(404).json({
success: false,
message: "Route Not Found",
});
});
// Centralized Error Catching
app.use((err, req, res, next) => {
console.log(err);
res.status(err.statusCode || 500).json({
success: false,
message: err.message || "Internal Server Error",
});
});
// Initialization of DB
async function initDB() {
try {
// PostgreSQL check
const result = await pool.query("SELECT NOW()");
console.log("Database Connected");
console.log(result.rows[0]);
await pool.query(`CREATE EXTENSION IF NOT EXISTS "pgcrypto";`);
await productTable();
await userTable();
await productMediaTable();
await inventoryTable();
await inventoryMovementTable();
await cartTable();
await cartItemTable();
console.log({
ProductTable: "Ready",
UserTable: "Ready",
ProductMediaTable: "Ready",
InventoryTable: "Ready",
InventoryMovementTable: "Ready",
CartTable: "Ready",
cartItemTable: "Ready",
});
// Redis check
await redisClient.connect();
console.log("Redis Connected");
// optional sanity test
await redisClient.set("health-check", "ok");
const test = await redisClient.get("health-check");
console.log("Redis Test Value:", test);
} catch (err) {
console.error("Database Connection Failed");
console.error(err);
process.exit(1);
}
}
// Server Listening
async function startServer() {
await initDB();
// Seed Script
if (process.env.RUN_SEED_ADMIN === "true") {
try {
await seedAminUser();
console.log("Admin user seeding completed");
} catch (error) {
console.error("Admin Seeding Failed", err.message);
}
}
app.listen(PORT, () => {
console.log(`Server is Running on http://localhost:${PORT}`);
});
}
startServer();