-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathserver.mjs
79 lines (70 loc) · 1.97 KB
/
server.mjs
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
import path, { dirname } from 'path'
import { fileURLToPath } from 'url'
import fastifyStatic from '@fastify/static'
import fastify from 'fastify'
import { h } from 'preact'
import { renderToString } from 'preact-render-to-string'
const app = fastify({ logger: true })
const __dirname = dirname(fileURLToPath(import.meta.url))
app.register(fastifyStatic, {
root: path.join(__dirname, 'out/client'),
prefix: '/client',
})
app.register(fastifyStatic, {
decorateReply: false,
root: path.join(__dirname, 'public'),
prefix: '/',
})
async function mapComponent(path, req, res) {
const appFile = await import('./out/_app.js')
const Component = await import(path)
let pageProps = {
props: {},
}
if ('getServerSideProps' in Component) {
Object.assign(
pageProps,
await Component.getServerSideProps({
request: req,
response: res,
query: req.query,
})
)
}
const mod = 'default' in appFile ? appFile.default : appFile
const FinalComponent = () =>
h(mod, {
Component: Component.default,
pageProps: pageProps.props,
})
const toString = renderToString(h(FinalComponent))
return toString
.replace(
/<\/head\>/,
'<link rel="stylesheet" href="/client/_app.css"></head>'
)
.replace(
/<\/body\>/,
`<script type="module" src="/client/${path.replace(
'./out/',
''
)}"></script>
<script type="application/json" id="pageProps">${JSON.stringify(
pageProps.props
)}</script>
</body>`
)
}
app.get('/', async (req, res) => {
res.header('content-type', 'text/html')
return mapComponent('./out/index.js', req, res)
})
app.get('/devices', async (req, res) => {
res.header('content-type', 'text/html')
return mapComponent('./out/devices.js', req, res)
})
app.get('/submit-rom', async (req, res) => {
res.header('content-type', 'text/html')
return mapComponent('./out/submit-rom.js', req, res)
})
await app.listen({ host: '0.0.0.0', port: 3000 })