-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
288 lines (255 loc) · 8.47 KB
/
Copy pathserver.js
File metadata and controls
288 lines (255 loc) · 8.47 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
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const path = require('path');
const fs = require('fs');
require('dotenv').config();
const app = express();
// Middleware
app.use(cors());
app.use(express.json());
// MongoDB connection
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/restaurant-booking', {
useNewUrlParser: true,
useUnifiedTopology: true
});
// Restaurant Schema
const restaurantSchema = new mongoose.Schema({
name: String,
cuisine: String,
address: String,
capacity: Number,
rating: Number,
image: String
});
const Restaurant = mongoose.model('Restaurant', restaurantSchema);
// Booking Schema
const bookingSchema = new mongoose.Schema({
restaurantId: { type: mongoose.Schema.Types.ObjectId, ref: 'Restaurant' },
date: Date,
time: String,
numberOfGuests: Number,
customerName: String,
customerEmail: String
});
const Booking = mongoose.model('Booking', bookingSchema);
// Mock data
const mockRestaurants = [
{
name: "La Bella Italia",
cuisine: "Italian",
address: "123 Main Street, Downtown",
capacity: 50,
rating: 4.8,
image: "https://images.unsplash.com/photo-1517248135467-4c7edcad34c4?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60"
},
{
name: "Sushi Master",
cuisine: "Japanese",
address: "456 Ocean Drive, Beachfront",
capacity: 40,
rating: 4.9,
image: "https://images.unsplash.com/photo-1579871494447-9811cf80d66c?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60"
},
{
name: "Taco Fiesta",
cuisine: "Mexican",
address: "789 Spice Street, Old Town",
capacity: 60,
rating: 4.7,
image: "https://images.unsplash.com/photo-1565299624946-b28f40a0ae38?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60"
},
{
name: "The Golden Fork",
cuisine: "French",
address: "321 Gourmet Avenue, Uptown",
capacity: 30,
rating: 4.9,
image: "https://images.unsplash.com/photo-1552566626-52f8b828add9?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60"
},
{
name: "Spice Garden",
cuisine: "Indian",
address: "654 Curry Lane, Midtown",
capacity: 45,
rating: 4.6,
image: "https://images.unsplash.com/photo-1517248135467-4c7edcad34c4?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60"
}
];
// Initialize mock data
const initializeMockData = async () => {
try {
const count = await Restaurant.countDocuments();
if (count === 0) {
await Restaurant.insertMany(mockRestaurants);
console.log('Mock restaurants added successfully');
}
} catch (error) {
console.error('Error initializing mock data:', error);
}
};
// Routes
app.get('/api/restaurants', async (req, res) => {
try {
const restaurants = await Restaurant.find();
res.json(restaurants);
} catch (error) {
res.status(500).json({ message: error.message });
}
});
app.post('/api/bookings', async (req, res) => {
try {
const booking = new Booking(req.body);
const savedBooking = await booking.save();
res.status(201).json(savedBooking);
} catch (error) {
res.status(400).json({ message: error.message });
}
});
app.post('/api/deploy', async (req, res) => {
try {
const esbuild = require('esbuild');
const { execSync } = require('child_process');
const clientDir = path.join(__dirname, 'client');
const buildDir = path.join(clientDir, 'build');
const workerDir = path.join(__dirname, 'worker');
const workerEntryPoint = path.join(workerDir, 'worker.js');
const distDir = path.join(__dirname, 'dist');
const outfile = path.join(distDir, 'worker.mjs');
if (!fs.existsSync(distDir)) {
fs.mkdirSync(distDir, { recursive: true });
}
// Step 1: Build the React app
execSync('npm run build', {
cwd: clientDir,
stdio: 'pipe',
env: { ...process.env, GENERATE_SOURCEMAP: 'false' }
});
// Step 2: Walk build output and base64-encode all files
const CONTENT_TYPES = {
'.html': 'text/html; charset=utf-8',
'.js': 'application/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.ico': 'image/x-icon',
'.png': 'image/png',
'.svg': 'image/svg+xml',
'.txt': 'text/plain',
};
function walkBuild(dir, baseDir, assets = {}) {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
walkBuild(full, baseDir, assets);
} else {
const ext = path.extname(entry.name).toLowerCase();
if (ext === '.map') continue; // skip source maps
const urlPath = '/' + path.relative(baseDir, full).replace(/\\/g, '/');
assets[urlPath] = {
content: fs.readFileSync(full).toString('base64'),
contentType: CONTENT_TYPES[ext] || 'application/octet-stream'
};
}
}
return assets;
}
const assets = walkBuild(buildDir, buildDir);
const assetsModule = `export const STATIC_ASSETS = ${JSON.stringify(assets)};`;
fs.writeFileSync(path.join(workerDir, 'static-assets.js'), assetsModule);
// Step 3: Bundle with esbuild (worker.js imports static-assets.js)
const result = await esbuild.build({
entryPoints: [workerEntryPoint],
bundle: true,
format: 'esm',
outfile: outfile,
target: 'esnext',
minify: true,
sourcemap: false,
metafile: true,
});
// Step 4: Size check
const bundleSizeMB = fs.statSync(outfile).size / (1024 * 1024);
if (bundleSizeMB > 10) {
return res.status(413).json({
success: false,
error: `Bundle too large: ${bundleSizeMB.toFixed(2)}MB exceeds 10MB Workers limit`
});
}
const bundleSizeKB = (fs.statSync(outfile).size / 1024).toFixed(2);
const warnings = result.warnings.map(w => w.text);
// Upload to Cloudflare Workers
const accountId = process.env.CLOUDFLARE_ACCOUNT_ID;
const apiToken = process.env.CLOUDFLARE_API_TOKEN;
if (!accountId || !apiToken) {
return res.status(500).json({
success: false,
error: 'Missing CLOUDFLARE_ACCOUNT_ID or CLOUDFLARE_API_TOKEN in .env'
});
}
const scriptName = 'restaurant-booking-app';
const bundleContent = fs.readFileSync(outfile);
const form = new FormData();
form.append('metadata', new Blob([JSON.stringify({
main_module: 'worker.mjs',
compatibility_date: '2025-09-15',
compatibility_flags: ['nodejs_compat'],
bindings: []
})], { type: 'application/json' }));
form.append('worker.mjs', new Blob([bundleContent], {
type: 'application/javascript+module'
}), 'worker.mjs');
const cfResponse = await fetch(
`https://api.cloudflare.com/client/v4/accounts/${accountId}/workers/scripts/${scriptName}`,
{
method: 'PUT',
headers: { 'Authorization': `Bearer ${apiToken}` },
body: form
}
);
const cfResult = await cfResponse.json();
if (!cfResult.success) {
return res.status(502).json({
success: false,
error: `Cloudflare upload failed: ${cfResult.errors.map(e => e.message).join(', ')}`,
details: cfResult.errors
});
}
// Enable the workers.dev subdomain route for this script
await fetch(
`https://api.cloudflare.com/client/v4/accounts/${accountId}/workers/scripts/${scriptName}/subdomain`,
{
method: 'POST',
headers: { 'Authorization': `Bearer ${apiToken}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ enabled: true })
}
);
// Fetch the real account workers subdomain
const subdomainRes = await fetch(
`https://api.cloudflare.com/client/v4/accounts/${accountId}/workers/subdomain`,
{ headers: { 'Authorization': `Bearer ${apiToken}` } }
);
const subdomainData = await subdomainRes.json();
const subdomain = subdomainData.result?.subdomain || accountId.slice(0, 8);
const workerUrl = `https://${scriptName}.${subdomain}.workers.dev`;
res.json({
success: true,
bundleSizeKB: parseFloat(bundleSizeKB),
warnings,
workerUrl,
scriptId: cfResult.result.id,
message: `Deployed! Live at ${workerUrl}`
});
} catch (error) {
console.error('Build error:', error);
res.status(500).json({
success: false,
error: error.message,
details: error.errors || []
});
}
});
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
initializeMockData();
});