-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
327 lines (281 loc) · 8.05 KB
/
Copy pathserver.js
File metadata and controls
327 lines (281 loc) · 8.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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
import fastify from "fastify";
import cors from "@fastify/cors";
import path from "path";
import { fileURLToPath } from "url";
import { AsyncDatabase } from "promised-sqlite3";
const server = fastify({
logger: {
transport: {
target: "pino-pretty",
},
},
});
// CORS: allow your Netlify app and local dev
await server.register(cors, {
origin: [
"https://resilient-dolphin-5c9b1d.netlify.app",
"http://localhost:5173",
],
methods: ["GET", "POST", "OPTIONS"],
allowedHeaders: ["Content-Type", "Authorization"],
// credentials: true, // <-- ONLY if you use cookies/auth; then remove "*" origins
maxAge: 600, // cache preflight for 10 minutes
});
const PORT = process.env.PORT || 3000;
const HOST = "RENDER" in process.env ? `0.0.0.0` : `localhost`;
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const db = await AsyncDatabase.open("./pizza.sqlite");
server.get("/api/pizzas", async function getPizzas(req, res) {
const pizzasPromise = db.all(
"SELECT pizza_type_id, name, category, ingredients as description FROM pizza_types"
);
const pizzaSizesPromise = db.all(
`SELECT
pizza_type_id as id, size, price
FROM
pizzas
`
);
const [pizzas, pizzaSizes] = await Promise.all([
pizzasPromise,
pizzaSizesPromise,
]);
const responsePizzas = pizzas.map((pizza) => {
const sizes = pizzaSizes.reduce((acc, current) => {
if (current.id === pizza.pizza_type_id) {
acc[current.size] = +current.price;
}
return acc;
}, {});
return {
id: pizza.pizza_type_id,
name: pizza.name,
category: pizza.category,
description: pizza.description,
image: `/pizzas/${pizza.pizza_type_id}.webp`,
sizes,
};
});
res.send(responsePizzas);
});
server.get("/api/pizza-of-the-day", async function getPizzaOfTheDay(req, res) {
const pizzas = await db.all(
`SELECT
pizza_type_id as id, name, category, ingredients as description
FROM
pizza_types`
);
const daysSinceEpoch = Math.floor(Date.now() / 86400000);
const pizzaIndex = daysSinceEpoch % pizzas.length;
const pizza = pizzas[pizzaIndex];
const sizes = await db.all(
`SELECT
size, price
FROM
pizzas
WHERE
pizza_type_id = ?`,
[pizza.id]
);
const sizeObj = sizes.reduce((acc, current) => {
acc[current.size] = +current.price;
return acc;
}, {});
const responsePizza = {
id: pizza.id,
name: pizza.name,
category: pizza.category,
description: pizza.description,
image: `/pizzas/${pizza.id}.webp`,
sizes: sizeObj,
};
res.send(responsePizza);
});
server.get("/api/orders", async function getOrders(req, res) {
const id = req.query.id;
const orders = await db.all("SELECT order_id, date, time FROM orders");
res.send(orders);
});
server.get("/api/order", async function getOrders(req, res) {
const id = req.query.id;
const orderPromise = db.get(
"SELECT order_id, date, time FROM orders WHERE order_id = ?",
[id]
);
const orderItemsPromise = db.all(
`SELECT
t.pizza_type_id as pizzaTypeId, t.name, t.category, t.ingredients as description, o.quantity, p.price, o.quantity * p.price as total, p.size
FROM
order_details o
JOIN
pizzas p
ON
o.pizza_id = p.pizza_id
JOIN
pizza_types t
ON
p.pizza_type_id = t.pizza_type_id
WHERE
order_id = ?`,
[id]
);
const [order, orderItemsRes] = await Promise.all([
orderPromise,
orderItemsPromise,
]);
const orderItems = orderItemsRes.map((item) =>
Object.assign({}, item, {
image: `/pizzas/${item.pizzaTypeId}.webp`,
quantity: +item.quantity,
price: +item.price,
})
);
const total = orderItems.reduce((acc, item) => acc + item.total, 0);
res.send({
order: Object.assign({ total }, order),
orderItems,
});
});
server.post("/api/order", async function createOrder(req, res) {
const { cart } = req.body;
const now = new Date();
// forgive me Date gods, for I have sinned
const time = now.toLocaleTimeString("en-US", { hour12: false });
const date = now.toISOString().split("T")[0];
if (!cart || !Array.isArray(cart) || cart.length === 0) {
res.status(400).send({ error: "Invalid order data" });
return;
}
try {
await db.run("BEGIN TRANSACTION");
const result = await db.run(
"INSERT INTO orders (date, time) VALUES (?, ?)",
[date, time]
);
const orderId = result.lastID;
const mergedCart = cart.reduce((acc, item) => {
const id = item.pizza.id;
const size = item.size.toLowerCase();
if (!id || !size) {
throw new Error("Invalid item data");
}
const pizzaId = `${id}_${size}`;
if (!acc[pizzaId]) {
acc[pizzaId] = { pizzaId, quantity: 1 };
} else {
acc[pizzaId].quantity += 1;
}
return acc;
}, {});
for (const item of Object.values(mergedCart)) {
const { pizzaId, quantity } = item;
await db.run(
"INSERT INTO order_details (order_id, pizza_id, quantity) VALUES (?, ?, ?)",
[orderId, pizzaId, quantity]
);
}
await db.run("COMMIT");
res.send({ orderId });
} catch (error) {
req.log.error(error);
await db.run("ROLLBACK");
res.status(500).send({ error: "Failed to create order" });
}
});
// server.addHook("preHandler", (req, res, done) => {
// res.header("Access-Control-Allow-Origin", "*");
// res.header("Access-Control-Allow-Methods", "GET, POST");
// res.header("Access-Control-Allow-Headers", "*");
// const isPreflight = /options/i.test(req.method);
// if (isPreflight) {
// return res.send();
// }
// done();
// });
server.get("/api/past-orders", async function getPastOrders(req, res) {
try {
const page = parseInt(req.query.page, 10) || 1;
const limit = 20;
const offset = (page - 1) * limit;
const pastOrders = await db.all(
"SELECT order_id, date, time FROM orders ORDER BY order_id DESC LIMIT 10 OFFSET ?",
[offset]
);
res.send(pastOrders);
} catch (error) {
req.log.error(error);
res.status(500).send({ error: "Failed to fetch past orders" });
}
});
server.get("/api/past-order/:order_id", async function getPastOrder(req, res) {
const orderId = req.params.order_id;
try {
const order = await db.get(
"SELECT order_id, date, time FROM orders WHERE order_id = ?",
[orderId]
);
if (!order) {
res.status(404).send({ error: "Order not found" });
return;
}
const orderItems = await db.all(
`SELECT
t.pizza_type_id as pizzaTypeId, t.name, t.category, t.ingredients as description, o.quantity, p.price, o.quantity * p.price as total, p.size
FROM
order_details o
JOIN
pizzas p
ON
o.pizza_id = p.pizza_id
JOIN
pizza_types t
ON
p.pizza_type_id = t.pizza_type_id
WHERE
order_id = ?`,
[orderId]
);
const formattedOrderItems = orderItems.map((item) =>
Object.assign({}, item, {
image: `/pizzas/${item.pizzaTypeId}.webp`,
quantity: +item.quantity,
price: +item.price,
})
);
const total = formattedOrderItems.reduce(
(acc, item) => acc + item.total,
0
);
res.send({
order: Object.assign({ total }, order),
orderItems: formattedOrderItems,
});
} catch (error) {
req.log.error(error);
res.status(500).send({ error: "Failed to fetch order" });
}
});
server.post("/api/contact", async function contactForm(req, res) {
const { name, email, message } = req.body;
if (!name || !email || !message) {
res.status(400).send({ error: "All fields are required" });
return;
}
req.log.info(`Contact Form Submission:
Name: ${name}
Email: ${email}
Message: ${message}
`);
res.send({ success: "Message received" });
});
const start = async () => {
try {
await server.listen({ host: HOST, port: PORT });
console.log(`Server listening on port ${PORT}`);
} catch (err) {
console.error(err);
process.exit(1);
}
};
start();