-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvite.config.dev.js
More file actions
216 lines (199 loc) · 7.8 KB
/
Copy pathvite.config.dev.js
File metadata and controls
216 lines (199 loc) · 7.8 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
import react from '@vitejs/plugin-react'
import { defineConfig } from 'vite'
import path from 'path'
import fs from 'fs'
// Helper to manage a local mock database
const DB_PATH = path.resolve(process.cwd(), 'db.json');
const getDb = () => {
if (!fs.existsSync(DB_PATH)) {
fs.writeFileSync(DB_PATH, JSON.stringify({
users: [{ email: 'user@example.com', password: 'password', full_name: 'Default User', role: 'user', onboarding_complete: false }],
entities: {}
}, null, 2));
}
return JSON.parse(fs.readFileSync(DB_PATH, 'utf-8'));
};
const saveDb = (db) => fs.writeFileSync(DB_PATH, JSON.stringify(db, null, 2));
// https://vite.dev/config/
export default defineConfig({
base: '/',
logLevel: 'info',
resolve: {
alias: {
'@': path.resolve(process.cwd(), 'src'),
},
},
plugins: [
react(),
{
name: 'mock-api',
configureServer(server) {
server.middlewares.use(async (req, res, next) => {
if (!req.url.startsWith('/api')) return next();
try {
const db = getDb();
const url = new URL(req.url, `http://${req.headers.host}`);
const [unused, api, type, ...rest] = url.pathname.split('/');
res.setHeader('Content-Type', 'application/json');
// Handle Authentication
if (type === 'auth') {
const endpoint = rest[0];
if (endpoint === 'me' && req.method === 'GET') {
const token = req.headers.authorization?.split(' ')[1];
const user = db.users.find(u => u.email === token);
if (user) {
res.end(JSON.stringify(user));
} else {
res.statusCode = 401;
res.end(JSON.stringify({ message: 'Unauthorized' }));
}
return;
}
if (req.method === 'PATCH' && endpoint === 'me') {
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => {
try {
const data = JSON.parse(body);
const token = req.headers.authorization?.split(' ')[1];
const userIndex = db.users.findIndex(u => u.email === token);
if (userIndex !== -1) {
db.users[userIndex] = { ...db.users[userIndex], ...data };
saveDb(db);
res.end(JSON.stringify(db.users[userIndex]));
} else {
res.statusCode = 401;
res.end(JSON.stringify({ message: 'Unauthorized' }));
}
} catch (e) {
res.statusCode = 400;
res.end(JSON.stringify({ message: 'Invalid JSON' }));
}
});
return;
}
if (req.method === 'POST') {
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => {
try {
const data = JSON.parse(body);
if (endpoint === 'login') {
const user = db.users.find(u => u.email === data.email && u.password === data.password);
if (user) {
res.end(JSON.stringify({ token: user.email, user }));
} else {
res.statusCode = 401;
res.end(JSON.stringify({ message: 'Invalid credentials' }));
}
} else if (endpoint === 'register') {
if (db.users.find(u => u.email === data.email)) {
res.statusCode = 400;
res.end(JSON.stringify({ message: 'User already exists' }));
} else {
const newUser = { ...data, onboarding_complete: false };
db.users.push(newUser);
saveDb(db);
res.end(JSON.stringify({ token: newUser.email, user: newUser }));
}
}
} catch (e) {
res.statusCode = 400;
res.end(JSON.stringify({ message: 'Invalid JSON' }));
}
});
return;
}
if (endpoint === 'google') {
res.writeHead(302, { Location: '/login?token=test123@gmail.com' });
res.end();
return;
}
}
// Handle Entities
if (type === 'entities') {
const entityName = rest[0];
const list = db[entityName] || db.entities[entityName] || [];
if (req.method === 'GET') {
res.end(JSON.stringify(list));
return;
}
if (req.method === 'POST') {
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => {
try {
const data = JSON.parse(body);
data.id = Math.random().toString(36).substr(2, 9);
if (db[entityName] && Array.isArray(db[entityName])) {
db[entityName].push(data);
} else {
db.entities[entityName] = db.entities[entityName] || [];
db.entities[entityName].push(data);
}
saveDb(db);
res.end(JSON.stringify(data));
} catch (e) {
res.statusCode = 400;
res.end(JSON.stringify({ message: 'Invalid JSON' }));
}
});
return;
}
if (req.method === 'PATCH') {
const id = rest[1];
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => {
try {
const data = JSON.parse(body);
const targetList = db[entityName] || db.entities[entityName] || [];
const index = targetList.findIndex(e => e.id == id);
if (index !== -1) {
targetList[index] = { ...targetList[index], ...data };
saveDb(db);
res.end(JSON.stringify(targetList[index]));
} else {
res.statusCode = 404;
res.end(JSON.stringify({ message: 'Not found' }));
}
} catch (e) {
res.statusCode = 400;
res.end(JSON.stringify({ message: 'Invalid JSON' }));
}
});
return;
}
if (req.method === 'DELETE') {
const id = rest[1];
const targetList = db[entityName] || db.entities[entityName] || [];
const index = targetList.findIndex(e => e.id == id);
if (index !== -1) {
targetList.splice(index, 1);
saveDb(db);
res.statusCode = 204;
res.end();
} else {
res.statusCode = 404;
res.end(JSON.stringify({ message: 'Not found' }));
}
return;
}
}
} catch (error) {
console.error('Mock API Error:', error);
res.statusCode = 500;
res.end(JSON.stringify({ message: 'Internal Server Error' }));
return;
}
next();
});
}
}
],
server: {
open: true,
host: 'localhost',
port: 3000,
},
});