Repository navigation
Expand file tree
/
Copy pathvite.config.js
More file actions
70 lines (62 loc) · 1.96 KB
/
Copy pathvite.config.js
File metadata and controls
70 lines (62 loc) · 1.96 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
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import users from './api/users.json' with { type: 'json' };
// A tiny API served by Vite itself:
// GET /api/users/:id read one user
// PATCH /api/users/:id change some of a user's fields (a city of "Atlantis" answers 500)
// Alice's answer is slowed down on purpose, so her requests
// are easy to see in the Network tab.
const DELAY_MS = { alice: 2000 };
const DEFAULT_MS = 400;
const PATCH_MS = 600;
// The "database": a copy of users.json in memory.
// Restarting the dev server puts everyone back.
const db = structuredClone(users);
function usersApi(req, res, next) {
const match = req.url.match(/^\/api\/users\/(\w+)$/);
if (!match) return next();
const id = match[1];
if (req.method === 'PATCH') return patchUser(id, req, res);
setTimeout(() => {
const user = db[id];
if (!user) {
res.statusCode = 404;
return res.end('Not found');
}
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(user));
}, DELAY_MS[id] ?? DEFAULT_MS);
}
function patchUser(id, req, res) {
let body = '';
req.on('data', (chunk) => (body += chunk));
req.on('end', () => {
setTimeout(() => {
if (!db[id]) {
res.statusCode = 404;
return res.end('Not found');
}
const changes = JSON.parse(body);
// One city the server refuses, so a failed save can be shown for real.
if (changes.city === 'Atlantis') {
res.statusCode = 500;
return res.end('No such city');
}
db[id] = { ...db[id], ...changes };
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(db[id]));
}, PATCH_MS);
});
}
const usersPlugin = {
name: 'users-api',
configureServer(server) {
server.middlewares.use(usersApi);
},
configurePreviewServer(server) {
server.middlewares.use(usersApi);
},
};
export default defineConfig({
plugins: [react(), usersPlugin],
});