-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
174 lines (159 loc) · 5.05 KB
/
Copy pathserver.js
File metadata and controls
174 lines (159 loc) · 5.05 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
import http from "http";
import fs from "fs/promises";
import path from "path";
import { fileURLToPath } from "url";
import { connectDB, db } from "./db.js";
import crypto from "crypto";
(async () => {
try {
await connectDB();
console.log("MongoDB ready");
} catch (err) {
console.error("MongoDB failed:", err);
}
})();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const publicDir = path.join(__dirname, "public"); // frontend root folder
function getSessionId(req, res) {
const cookie = req.headers.cookie || "";
const match = cookie.match(/sessionId=([^;]+)/);
if (match) {
return match[1];
}
const sessionId = crypto.randomUUID();
res.setHeader(
"Set-Cookie",
`sessionId=${sessionId};Path=/;HttpOnly;Max-Age=2592000;SameSite=Lax;`
);
return sessionId;
}
const server = http.createServer(async (req, res) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
const sessionId = getSessionId(req, res);
if (req.method === "OPTIONS") {
res.writeHead(204);
res.end();
return;
}
// ------------------------- PUBLIC FRONTEND -------------------------
if (req.method === "GET" && !req.url.startsWith("/api")) {
const parsedUrl = new URL(req.url, `http://${req.headers.host}`);
const pathname = parsedUrl.pathname;
let safePath = pathname;
if (pathname === "/" || pathname === "/amazon") {
safePath = "/index.html";
} else if (pathname === "/tracking") {
safePath = "/tracking.html";
}
const filePath = path.join(publicDir, safePath);
try {
const data = await fs.readFile(filePath);
const ext = path.extname(filePath);
const contentTypes = {
".html": "text/html",
".js": "application/javascript",
".css": "text/css",
".json": "application/json",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".svg": "image/svg+xml",
".webp": "image/webp",
};
res.writeHead(200, {
"Content-Type": contentTypes[ext] || "application/octet-stream",
});
res.end(data);
} catch {
const html = await fs.readFile(path.join(publicDir, "index.html"));
res.writeHead(200, { "Content-Type": "text/html" });
res.end(html);
}
return;
}
// ------------------------- API ROUTES -------------------------
// PRODUCTS
if (req.method === "GET" && req.url === "/api/products") {
const filePath = path.join(__dirname, "data", "products.json");
const data = await fs.readFile(filePath, "utf-8");
res.writeHead(200, { "Content-Type": "application/json" });
res.end(data);
return;
}
// CART POST
if (req.method === "POST" && req.url === "/api/cart") {
let body = "";
req.on("data", (chunk) => (body += chunk));
req.on("end", async () => {
try {
const cartData = JSON.parse(body);
await db.collection("carts").updateOne(
{ sessionId },
{
$set: {
items: cartData.items,
updatedAt: new Date(),
},
},
{ upsert: true }
);
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ success: true }));
} catch {
res.writeHead(400, { "Content-Type": "application/json" });
res.end(JSON.stringify({ success: false }));
}
});
return;
}
// CART GET
if (req.method === "GET" && req.url === "/api/cart") {
const cartData = await db.collection("carts").findOne({ sessionId });
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(cartData ?? { items: [] }));
return;
}
// ORDERS GET
if (req.method === "GET" && req.url === "/api/orders") {
const ordersData = await db
.collection("orders")
.find({ sessionId })
.sort({ createdTime: -1 })
.toArray();
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ orders: ordersData }));
return;
}
// ORDERS POST
if (req.method === "POST" && req.url === "/api/orders") {
let body = "";
req.on("data", (chunk) => (body += chunk));
req.on("end", async () => {
try {
const newOrder = JSON.parse(body);
const orderId = crypto.randomUUID();
await db.collection("orders").insertOne({
...newOrder,
sessionId,
orderId,
createdTime: new Date(),
});
res.writeHead(201, { "Content-Type": "application/json" });
res.end(JSON.stringify({ orderId, success: true }));
} catch {
res.writeHead(400, { "Content-Type": "application/json" });
res.end(JSON.stringify({ success: false }));
}
});
return;
}
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Not Found");
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log("Server Running", PORT);
});