-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathserver.js
70 lines (54 loc) · 1.71 KB
/
server.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
68
69
70
import express from 'express'
import { readFileSync, writeFileSync } from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'
import { createServer as createViteServer } from 'vite'
const port = 5173
const cachePath = './cache.json'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
// Using cache to reload parsed feeds from disk instead of remote
// Since every change of the email is a full render it feels wasteful retrieving the RSS
const getCache = () => {
try {
let cache = readFileSync(cachePath, 'utf-8')
return JSON.parse(cache)
} catch {
return
}
}
async function createServer() {
const app = express()
const vite = await createViteServer({
server: { middlewareMode: true },
appType: 'custom',
})
app.use(vite.middlewares)
app.use('/preview.html', async (_, res, next) => {
try {
const { renderEmail } = await vite.ssrLoadModule('/src/renderEmail.tsx')
const { html, feeds } = await renderEmail({
pretty: true,
cache: getCache(),
})
writeFileSync(cachePath, JSON.stringify(feeds), { flag: 'w' })
res.status(200).set({ 'Content-Type': 'text/html' }).end(html)
} catch (e) {
vite.ssrFixStacktrace(e)
next(e)
}
})
app.use('/', async (req, res, next) => {
const url = req.originalUrl
try {
let template = readFileSync(path.resolve(__dirname, 'index.html'), 'utf-8')
template = await vite.transformIndexHtml(url, template)
res.status(200).set({ 'Content-Type': 'text/html' }).end(template)
} catch (e) {
vite.ssrFixStacktrace(e)
next(e)
}
})
app.listen(port)
console.log(`Preview started on: http://localhost:${port}`)
}
createServer()