Nuxt/lib/app/server.js

215 lines
7.2 KiB
JavaScript
Raw Normal View History

2016-11-07 01:34:58 +00:00
import Vue from 'vue'
2016-11-10 23:01:36 +00:00
import { stringify } from 'querystring'
import omit from 'lodash/omit'
2017-02-03 14:09:27 +00:00
import middleware from './middleware'
2017-05-02 06:57:39 +00:00
import { createApp, NuxtError } from './index'
2017-07-09 14:50:55 +00:00
import { applyAsyncData, sanitizeComponent, getMatchedComponents, getContext, middlewareSeries, promisify, urlJoin } from './utils'
2017-07-09 11:43:03 +00:00
2017-05-04 07:57:10 +00:00
const debug = require('debug')('nuxt:render')
debug.color = 4 // force blue color
2016-11-07 01:34:58 +00:00
const isDev = <%= isDev %>
2016-11-07 01:34:58 +00:00
2017-07-09 11:43:03 +00:00
const noopApp = () => new Vue({ render: (h) => h('div') })
const createNext = (ssrContext) => (opts) => {
ssrContext.redirected = opts
2017-07-09 11:43:03 +00:00
// If nuxt generate
if (!ssrContext.res) {
ssrContext.nuxt.serverRendered = false
2017-07-09 11:43:03 +00:00
return
}
opts.query = stringify(opts.query)
opts.path = opts.path + (opts.query ? '?' + opts.query : '')
if (opts.path.indexOf('http') !== 0 && ('<%= router.base %>' !== '/' && opts.path.indexOf('<%= router.base %>') !== 0)) {
opts.path = urlJoin('<%= router.base %>', opts.path)
}
// Avoid loop redirect
if (opts.path === ssrContext.url) {
ssrContext.redirected = false
2017-07-09 11:43:03 +00:00
return
}
ssrContext.res.writeHead(opts.status, {
2017-07-09 11:43:03 +00:00
'Location': opts.path
})
ssrContext.res.end()
2017-07-09 11:43:03 +00:00
}
2016-11-07 01:34:58 +00:00
// This exported function will be called by `bundleRenderer`.
// This is where we perform data-prefetching to determine the
// state of our application before actually rendering it.
// Since data fetching is async, this function is expected to
// return a Promise that resolves to the app instance.
export default async (ssrContext) => {
// Create ssrContext.next for simulate next() of beforeEach() when wanted to redirect
ssrContext.redirected = false
ssrContext.next = createNext(ssrContext)
// Used for beforeNuxtRender({ Components, nuxtState })
ssrContext.beforeRenderFns = []
// Nuxt object (window.__NUXT__)
ssrContext.nuxt = { layout: 'default', data: [], error: null<%= (store ? ', state: null' : '') %>, serverRendered: true }
// Create the app definition and the instance (created for each request)
const { app, router<%= (store ? ', store' : '') %> } = await createApp(ssrContext)
2017-06-06 12:51:49 +00:00
const _app = new Vue(app)
2017-07-27 14:26:59 +00:00
// Add meta infos (used in renderer.js)
ssrContext.meta = _app.$meta()
// Keep asyncData for each matched component in ssrContext (used in app/utils.js via this.$ssrContext)
ssrContext.asyncData = {}
const beforeRender = async () => {
// Call beforeNuxtRender() methods
await Promise.all(ssrContext.beforeRenderFns.map((fn) => promisify(fn, { Components, nuxtState: ssrContext.nuxt })))
<% if (store) { %>
// Add the state from the vuex store
ssrContext.nuxt.state = store.state
<% } %>
}
const renderErrorPage = async () => {
// Load layout for error page
let errLayout = (typeof NuxtError.layout === 'function' ? NuxtError.layout(app.context) : NuxtError.layout)
2017-11-06 17:30:37 +00:00
ssrContext.nuxt.layout = errLayout || 'default'
await _app.loadLayout(errLayout)
_app.setLayout(errLayout)
await beforeRender()
return _app
}
const render404Page = () => {
2018-07-12 20:45:14 +00:00
app.context.error({ statusCode: 404, path: ssrContext.url, message: `<%= messages.error_404 %>` })
return renderErrorPage()
}
2017-07-09 11:43:03 +00:00
<% if (isDev) { %>const s = isDev && Date.now()<% } %>
2017-07-27 14:26:59 +00:00
// Components are already resolved by setContext -> getRouteData (app/utils.js)
const Components = getMatchedComponents(router.match(ssrContext.url))
2017-07-09 11:43:03 +00:00
2017-07-09 12:02:26 +00:00
<% if (store) { %>
/*
** Dispatch store nuxtServerInit
*/
2017-07-09 11:43:03 +00:00
if (store._actions && store._actions.nuxtServerInit) {
try {
await store.dispatch('nuxtServerInit', app.context)
} catch (err) {
2017-11-10 21:51:10 +00:00
debug('error occurred when calling nuxtServerInit: ', err.message)
throw err
}
2017-07-09 11:43:03 +00:00
}
// ...If there is a redirect or an error, stop the process
if (ssrContext.redirected) return noopApp()
if (ssrContext.nuxt.error) return renderErrorPage()
2017-07-09 12:02:26 +00:00
<% } %>
2017-07-09 11:43:03 +00:00
/*
** Call global middleware (nuxt.config.js)
*/
let midd = <%= serialize(router.middleware).replace('middleware(', 'function(') %>
2017-05-04 07:57:10 +00:00
midd = midd.map((name) => {
2017-11-03 16:14:05 +00:00
if (typeof name === 'function') return name
2017-05-04 07:57:10 +00:00
if (typeof middleware[name] !== 'function') {
app.context.error({ statusCode: 500, message: 'Unknown middleware ' + name })
2017-05-04 07:57:10 +00:00
}
return middleware[name]
2017-03-17 17:02:58 +00:00
})
await middlewareSeries(midd, app.context)
// ...If there is a redirect or an error, stop the process
if (ssrContext.redirected) return noopApp()
if (ssrContext.nuxt.error) return renderErrorPage()
/*
** Set layout
*/
2017-05-04 07:57:10 +00:00
let layout = Components.length ? Components[0].options.layout : NuxtError.layout
if (typeof layout === 'function') layout = layout(app.context)
2017-05-04 07:57:10 +00:00
await _app.loadLayout(layout)
if (ssrContext.nuxt.error) return renderErrorPage()
2017-05-04 07:57:10 +00:00
layout = _app.setLayout(layout)
2017-07-09 11:43:03 +00:00
// ...Set layout to __NUXT__
ssrContext.nuxt.layout = _app.layoutName
2017-07-27 14:26:59 +00:00
/*
** Call middleware (layout + pages)
*/
midd = []
if (layout.middleware) midd = midd.concat(layout.middleware)
Components.forEach((Component) => {
if (Component.options.middleware) {
midd = midd.concat(Component.options.middleware)
}
})
midd = midd.map((name) => {
2017-11-03 16:14:05 +00:00
if (typeof name === 'function') return name
if (typeof middleware[name] !== 'function') {
app.context.error({ statusCode: 500, message: 'Unknown middleware ' + name })
}
return middleware[name]
})
await middlewareSeries(midd, app.context)
// ...If there is a redirect or an error, stop the process
if (ssrContext.redirected) return noopApp()
if (ssrContext.nuxt.error) return renderErrorPage()
/*
** Call .validate()
*/
2017-05-04 07:57:10 +00:00
let isValid = true
Components.forEach((Component) => {
if (!isValid) return
if (typeof Component.options.validate !== 'function') return
2018-03-14 10:03:17 +00:00
isValid = Component.options.validate(app.context)
2016-11-17 12:52:00 +00:00
})
2017-07-09 11:43:03 +00:00
// ...If .validate() returned false
2017-05-04 07:57:10 +00:00
if (!isValid) {
// Don't server-render the page in generate mode
if (ssrContext._generate) ssrContext.nuxt.serverRendered = false
// Render a 404 error page
return render404Page()
2017-05-04 07:57:10 +00:00
}
2017-07-27 14:26:59 +00:00
// If no Components found, returns 404
if (!Components.length) return render404Page()
2017-05-04 07:57:10 +00:00
// Call asyncData & fetch hooks on components matched by the route.
let asyncDatas = await Promise.all(Components.map((Component) => {
2017-05-04 07:57:10 +00:00
let promises = []
2017-07-27 14:26:59 +00:00
2017-07-09 11:43:03 +00:00
// Call asyncData(context)
2017-05-04 07:57:10 +00:00
if (Component.options.asyncData && typeof Component.options.asyncData === 'function') {
let promise = promisify(Component.options.asyncData, app.context)
promise.then((asyncDataResult) => {
ssrContext.asyncData[Component.cid] = asyncDataResult
applyAsyncData(Component)
2017-05-04 07:57:10 +00:00
return asyncDataResult
})
promises.push(promise)
2017-07-09 11:43:03 +00:00
} else {
promises.push(null)
}
// Call fetch(context)
2017-07-09 11:43:03 +00:00
if (Component.options.fetch) {
promises.push(Component.options.fetch(app.context))
2017-07-09 11:43:03 +00:00
}
else {
promises.push(null)
}
2017-07-09 21:06:17 +00:00
return Promise.all(promises)
2017-05-04 07:57:10 +00:00
}))
2017-07-27 14:26:59 +00:00
<% if (isDev) { %>if (asyncDatas.length) debug('Data fetching ' + ssrContext.url + ': ' + (Date.now() - s) + 'ms')<% } %>
2017-07-09 11:43:03 +00:00
2017-05-04 07:57:10 +00:00
// datas are the first row of each
ssrContext.nuxt.data = asyncDatas.map(r => r[0] || {})
2017-07-09 11:43:03 +00:00
// ...If there is a redirect or an error, stop the process
if (ssrContext.redirected) return noopApp()
if (ssrContext.nuxt.error) return renderErrorPage()
2017-07-27 14:26:59 +00:00
// Call beforeNuxtRender methods & add store state
await beforeRender()
2017-05-04 07:57:10 +00:00
return _app
2016-11-07 01:34:58 +00:00
}