1 | const Endpoint = require('cubic-api/endpoint')
|
2 | const util = require('util')
|
3 | const fs = require('fs')
|
4 | const readFile = util.promisify(fs.readFile)
|
5 | const path = require('path')
|
6 | const publicPath = `${cubic.config.ui.api.publicPath}/bundles`
|
7 | const createBundleRenderer = require('vue-server-renderer').createBundleRenderer
|
8 | const { promisify } = require('util')
|
9 | const fileExists = promisify(fs.lstat)
|
10 | const Client = require('cubic-client')
|
11 | const user = cubic.nodes.auth ? cubic.nodes.auth.api.systemUser : {}
|
12 |
|
13 |
|
14 | let api
|
15 | if (!cubic.config.ui.client.disableSsr) {
|
16 | api = new Client({
|
17 | api_url: cubic.config.ui.server.apiUrl,
|
18 | auth_url: cubic.config.ui.server.authUrl,
|
19 | user_key: user.user_key || cubic.config.ui.server.user_key,
|
20 | user_secret: user.user_secret || cubic.config.ui.server.user_secret
|
21 | })
|
22 | }
|
23 |
|
24 |
|
25 |
|
26 |
|
27 | let bundlesReady = false
|
28 | async function awaitBundles () {
|
29 | return new Promise(async resolve => {
|
30 | try {
|
31 | await fileExists(`${publicPath}/vue-ssr-client-manifest.json`)
|
32 | await fileExists(`${publicPath}/vue-ssr-server-bundle.json`)
|
33 | bundlesReady = true
|
34 | resolve()
|
35 | } catch (err) {
|
36 | setTimeout(async () => {
|
37 | resolve(await awaitBundles())
|
38 | }, 500)
|
39 | }
|
40 | })
|
41 | }
|
42 |
|
43 |
|
44 |
|
45 |
|
46 |
|
47 |
|
48 | class View extends Endpoint {
|
49 | |
50 |
|
51 |
|
52 | async main (req, res) {
|
53 | res.setHeader('content-type', 'text/html')
|
54 | return res.send(await this.render(req))
|
55 | }
|
56 |
|
57 | |
58 |
|
59 |
|
60 | async render (req) {
|
61 | if (!bundlesReady) await awaitBundles()
|
62 | const serverBundle = require(path.join(publicPath, 'vue-ssr-server-bundle.json'))
|
63 | const clientManifest = require(path.join(publicPath, 'vue-ssr-client-manifest.json'))
|
64 | const template = await readFile(path.join(__dirname, './vue/index.template.html'), 'utf-8')
|
65 | const renderer = createBundleRenderer(serverBundle, {
|
66 | template,
|
67 | clientManifest,
|
68 | runInNewContext: false
|
69 | })
|
70 | const render = util.promisify(renderer.renderToString)
|
71 | const context = { req, api }
|
72 | const html = await render(context)
|
73 | this.cache(html, cubic.config.ui.api.cacheExp, { 'content-type': 'text/html' })
|
74 | return html
|
75 | }
|
76 | }
|
77 |
|
78 | module.exports = View
|