You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
77 lines
2.4 KiB
JavaScript
77 lines
2.4 KiB
JavaScript
import express from 'express'
|
|
import { createServer as createViteServer } from 'vite'
|
|
import { getDevRoutesMetadata } from './meta/routes.js'
|
|
|
|
import fetch from 'node-fetch'
|
|
|
|
import { readFile } from 'fs/promises'
|
|
import { dirname, resolve } from 'path'
|
|
|
|
import morgan from 'morgan'
|
|
|
|
import { fileURLToPath } from 'url'
|
|
const __dirname = fileURLToPath(new URL('.', import.meta.url))
|
|
|
|
async function main() {
|
|
const routes = await getDevRoutesMetadata('http://127.0.0.1:4000/api/development/routes')
|
|
console.dir(routes)
|
|
|
|
const app = express()
|
|
|
|
app.use(morgan(':method :url :status :response-time ms - :res[content-length]'))
|
|
|
|
const vite = await createViteServer({
|
|
server: { middlewareMode: true },
|
|
appType: 'custom',
|
|
})
|
|
|
|
app.use(vite.middlewares)
|
|
|
|
Object.entries(routes.static).forEach(([route, file]) => {
|
|
app.get(route, async (_req, res) => {
|
|
let htmlPage = await readFile(resolve(__dirname, './frontend/', file), 'utf8')
|
|
htmlPage = htmlPage.replace(/\.\//g, '/' + dirname(file) + '/')
|
|
|
|
const html = await vite.transformIndexHtml(file, htmlPage)
|
|
console.dir(file)
|
|
|
|
res.writeHead(200, { 'Content-Type': 'text/html' }).end(html)
|
|
})
|
|
})
|
|
|
|
Object.entries(routes.dynamic).forEach(([route, file]) => {
|
|
app.get(route, async (req, res) => {
|
|
let htmlPage = await readFile(resolve(__dirname, './frontend/', file), 'utf8')
|
|
htmlPage = htmlPage.replace(/\.\//g, '/' + dirname(file) + '/')
|
|
|
|
const html = await vite.transformIndexHtml(file, htmlPage)
|
|
|
|
console.log('req.url = ', req.url)
|
|
console.log('req.originalUrl = ', req.originalUrl)
|
|
|
|
const templateHtmlReq = await fetch('http://127.0.0.1:4000/api/development/render', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
route,
|
|
page: html,
|
|
request: {
|
|
params: req.params,
|
|
query: req.query,
|
|
},
|
|
}),
|
|
})
|
|
|
|
const renderedHtml = await templateHtmlReq.json()
|
|
|
|
res.writeHead(200, { 'Content-Type': 'text/html' }).end(renderedHtml)
|
|
})
|
|
})
|
|
|
|
app.listen(3000, () => {
|
|
console.log(`Listening on port 3000...`)
|
|
})
|
|
}
|
|
|
|
main()
|