magic: added a way for running async functions in the top level jsx code
This commit is contained in:
@@ -10,6 +10,7 @@ import { createServer as createViteServer } from 'vite'
|
||||
|
||||
import { createApiRouter } from './server/routes'
|
||||
import { RenderFunction } from './shared/ssr'
|
||||
import { DatabaseConnection } from './shared/database'
|
||||
|
||||
// Load ".env"
|
||||
dotenv.config()
|
||||
@@ -24,7 +25,7 @@ if (config.isDevelopment) {
|
||||
console.log(`[Config] PORT = ${config.port}`)
|
||||
}
|
||||
|
||||
async function createDevRouter() {
|
||||
async function createDevRouter(db: DatabaseConnection) {
|
||||
const r = express.Router()
|
||||
|
||||
const vite = await createViteServer({
|
||||
@@ -41,7 +42,8 @@ async function createDevRouter() {
|
||||
// Load (to be bundled) entry point for server side rendering
|
||||
const render: RenderFunction = (await vite.ssrLoadModule('./client/entry-server.tsx')).default
|
||||
|
||||
const { html, metadata } = render(req.originalUrl)
|
||||
const { html, metadata, asyncCallbacks } = render(req.originalUrl, db)
|
||||
await Promise.all(asyncCallbacks.map(fn => fn()))
|
||||
|
||||
const fullUrl = `${req.protocol}://${req.get('host')}${req.originalUrl}`
|
||||
const metaTagsHtml =
|
||||
@@ -64,7 +66,7 @@ async function createDevRouter() {
|
||||
return r
|
||||
}
|
||||
|
||||
async function createProductionRouter() {
|
||||
async function createProductionRouter(db: DatabaseConnection) {
|
||||
// Load bundled entry point for server side rendering
|
||||
|
||||
// @ts-ignore
|
||||
@@ -75,11 +77,8 @@ async function createProductionRouter() {
|
||||
const handleSSR = async (req, res) => {
|
||||
const transformedTemplate = await fs.readFile(path.resolve('./dist/entry-client/index.html'), 'utf-8')
|
||||
|
||||
const { html, metadata } = render(req.originalUrl)
|
||||
|
||||
console.dir(transformedTemplate, { depth: null })
|
||||
console.dir(html, { depth: null })
|
||||
console.dir(metadata, { depth: null })
|
||||
const { html, metadata, asyncCallbacks } = render(req.originalUrl, db)
|
||||
await Promise.all(asyncCallbacks.map(fn => fn()))
|
||||
|
||||
const fullUrl = `${req.protocol}://${req.get('host')}${req.originalUrl}`
|
||||
const metaTagsHtml =
|
||||
@@ -112,12 +111,14 @@ async function main() {
|
||||
|
||||
app.use(morgan('[Request] :method :url :status :response-time ms - :res[content-length]'))
|
||||
|
||||
app.use('/', await createApiRouter())
|
||||
const [r, db] = await createApiRouter()
|
||||
|
||||
app.use('/', r)
|
||||
|
||||
if (config.isDevelopment) {
|
||||
app.use('/', await createDevRouter())
|
||||
app.use('/', await createDevRouter(db))
|
||||
} else {
|
||||
app.use('/', await createProductionRouter())
|
||||
app.use('/', await createProductionRouter(db))
|
||||
}
|
||||
|
||||
app.listen(config.port, () => {
|
||||
|
||||
Reference in New Issue
Block a user