-
Notifications
You must be signed in to change notification settings - Fork 32
/
plugin.js
67 lines (59 loc) · 1.77 KB
/
plugin.js
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
import viteSSRPlugin from 'vite-ssr/plugin.js'
export default {
...viteSSRPlugin,
alias: {
vitedge: 'vitedge/entry-client',
},
configureServer: [
async ({
root, // project root directory, absolute path
app, // Koa app instance
server, // raw http server instance
watcher, // chokidar file watcher instance
}) => {
const cacheBust = new Map()
watcher.on('change', (fullPath) => {
if (fullPath.replace(root, '').startsWith('/functions/')) {
const filePath = fullPath.replace(/\.[jt]sx?$/i, '')
cacheBust.set(filePath, (cacheBust.get(filePath) || 0) + 1)
}
})
async function handleFunctionRequest(ctx, functionPath) {
try {
const filePath = root + '/functions' + functionPath
let endpointMeta = await import(
filePath + '.js' + `?cacheBust=${cacheBust.get(filePath) || 0}`
)
if (endpointMeta) {
endpointMeta = endpointMeta.default || endpointMeta
if (endpointMeta.handler) {
ctx.body = await endpointMeta.handler({
request: ctx.request,
query: ctx.query,
body: ctx.request.body,
})
return
}
}
} catch (error) {
console.error(error)
ctx.message = error.message
ctx.status = 500
return
}
ctx.status = 404
}
app.use(async (ctx, next) => {
if (ctx.url.includes('/api/')) {
await handleFunctionRequest(ctx, ctx.url)
return
}
if (ctx.url.includes('/props/')) {
await handleFunctionRequest(ctx, ctx.query.propsGetter)
return
}
await next()
})
},
],
}