Nuxt/lib/app/server.js

279 lines
8.8 KiB
JavaScript
Raw Normal View History

2016-11-07 01:34:58 +00:00
import Vue from 'vue'
import clone from 'clone'
2016-11-10 23:01:36 +00:00
import { stringify } from 'querystring'
2016-11-17 13:02:09 +00:00
import { omit } from 'lodash'
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 11:43:03 +00:00
import { applyAsyncData, sanitizeComponent, getMatchedComponents, getContext, middlewareSeries, promisify, urlJoin} from './utils'
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 = context => opts => {
context.redirected = opts
// If nuxt generate
if (!context.res) {
context.nuxt.serverRendered = false
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 === context.url) {
context.redirected = false
return
}
context.res.writeHead(opts.status, {
'Location': opts.path
})
context.res.end()
}
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.
2017-07-09 11:43:03 +00:00
export default async context => {
// Create context.next for simulate next() of beforeEach() when wanted to redirect
2016-11-10 23:01:36 +00:00
context.redirected = false
2017-07-09 11:43:03 +00:00
context.next = createNext(context)
2017-06-06 12:51:49 +00:00
const { app, router<%= (store ? ', store' : '') %> } = await createApp(context)
const _app = new Vue(app)
2017-07-09 11:43:03 +00:00
2017-07-09 12:02:26 +00:00
<% if (store) { %>
2017-06-06 12:51:49 +00:00
// Add store to the context
2017-07-09 12:02:26 +00:00
context.store = store
<% } %>
2017-07-09 11:43:03 +00:00
2017-06-06 12:51:49 +00:00
// Add route to the context
context.route = router.currentRoute
2017-07-09 11:43:03 +00:00
// Components array (for dynamic components)
context.hasDynamicComponents = false
context.components = []
2017-07-09 11:43:03 +00:00
2017-06-06 12:51:49 +00:00
// Nuxt object
context.nuxt = { layout: 'default', data: [], error: null<%= (store ? ', state: null' : '') %>, serverRendered: true }
2017-07-09 11:43:03 +00:00
2016-11-07 01:34:58 +00:00
// Add meta infos
context.meta = _app.$meta()
2017-07-09 11:43:03 +00:00
// Error function
context.error = _app.$options._nuxt.error.bind(_app)
2017-07-09 11:43:03 +00:00
// Keep asyncData for each matched component in context
context.asyncData = {}
2016-11-07 01:34:58 +00:00
2017-07-09 11:43:03 +00:00
// Create shared ctx
const ctx = getContext(context, app)
<% if (isDev) { %>const s = isDev && Date.now()<% } %>
// Resolve components
2017-03-22 14:47:34 +00:00
let Components = []
2017-07-09 11:43:03 +00:00
try {
Components = await Promise.all(getMatchedComponents(router.match(context.url)).map((Component) => new Promise((resolve, reject) => {
if (typeof Component !== 'function' || Component.super === Vue) {
return resolve(sanitizeComponent(Component))
}
2017-05-04 07:57:10 +00:00
const _resolve = (Component) => resolve(sanitizeComponent(Component))
2017-03-24 00:28:19 +00:00
Component().then(_resolve).catch(reject)
2017-07-09 11:43:03 +00:00
})))
2017-05-04 07:57:10 +00:00
} catch (err) {
// Throw back error to renderRoute()
throw err
}
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) {
await store.dispatch('nuxtServerInit', ctx)
}
// ...If there is a redirect
if (context.redirected) return noopApp()
2017-07-09 12:02:26 +00:00
<% } %>
2017-07-09 11:43:03 +00:00
2017-05-04 07:57:10 +00:00
// Call global middleware (nuxt.config.js)
let midd = <%= serialize(router.middleware, { isJSON: true }) %>
midd = midd.map((name) => {
if (typeof middleware[name] !== 'function') {
context.nuxt.error = context.error({ statusCode: 500, message: 'Unknown middleware ' + name })
}
return middleware[name]
2017-03-17 17:02:58 +00:00
})
2017-05-04 07:57:10 +00:00
if (!context.nuxt.error) {
await middlewareSeries(midd, ctx)
}
2017-07-09 11:43:03 +00:00
// ...If there is a redirect
if (context.redirected) return noopApp()
2017-05-04 07:57:10 +00:00
// Set layout
let layout = Components.length ? Components[0].options.layout : NuxtError.layout
if (typeof layout === 'function') layout = layout(ctx)
await _app.loadLayout(layout)
layout = _app.setLayout(layout)
2017-07-09 11:43:03 +00:00
// ...Set layout to __NUXT__
2017-05-04 07:57:10 +00:00
context.nuxt.layout = _app.layoutName
2017-07-09 11:43:03 +00:00
2017-05-04 07:57:10 +00:00
// Call middleware (layout + pages)
if (!context.nuxt.error) {
2017-07-09 11:43:03 +00:00
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) => {
if (typeof middleware[name] !== 'function') {
context.nuxt.error = context.error({ statusCode: 500, message: 'Unknown middleware ' + name })
}
return middleware[name]
})
2017-05-04 07:57:10 +00:00
await middlewareSeries(midd, ctx)
2017-07-09 11:43:03 +00:00
// If there is a redirect
if (context.redirected) return noopApp()
2017-05-04 07:57:10 +00:00
}
2017-07-09 11:43:03 +00:00
2017-05-04 07:57:10 +00:00
// Call .validate()
let isValid = true
Components.forEach((Component) => {
if (!isValid) return
if (typeof Component.options.validate !== 'function') return
isValid = Component.options.validate({
params: context.route.params || {},
query: context.route.query || {}<%= (store ? ', store: ctx.store' : '') %>
2016-12-12 15:30:07 +00:00
})
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 (context._generate) {
context.nuxt.serverRendered = false
}
2017-05-04 07:57:10 +00:00
// Call the 404 error by making the Components array empty
Components = []
}
2017-07-09 11:43:03 +00:00
2017-05-04 07:57:10 +00:00
// Call asyncData & fetch hooks on components matched by the route.
2017-07-09 11:43:03 +00:00
let asyncDatas = await Promise.all(Components.map(Component => {
2017-05-04 07:57:10 +00:00
let promises = []
2017-07-09 11:43:03 +00:00
// Create this context for asyncData & fetch (used for dynamic component injection)
const _this = { components: {} }
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.bind(_this), ctx)
2017-07-09 11:43:03 +00:00
promise.then(asyncDataResult => {
context.asyncData[Component.options.name] = 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.call(_this, ctx))
}
else {
promises.push(null)
}
return Promise.all(promises).then(data => {
// If not dyanmic component, return data directly
2017-07-09 11:43:03 +00:00
if (Object.keys(_this.components).length === 0) {
return data
}
// Sanetize resolved components (Temporary workaround for vue-loader 13.0.0)
Object.keys(_this.components).forEach(name => {
_this.components[name] = _this.components[name].default || _this.components[name]
})
2017-07-09 11:43:03 +00:00
// Tell renderer that dynamic components has been added
context.hasDynamicComponents = true
2017-07-09 11:43:03 +00:00
// Add Component on server side (clone of it)
Component.options.components = {
...Component.options.components,
...clone(_this.components) // Clone it to avoid vue to overwrite references
}
2017-07-09 11:43:03 +00:00
// Add components into __NUXT__ for client-side hydration
// We clone it since vue-server-renderer will update the component definition
context.components.push(sanitizeDynamicComponents(_this.components))
2017-07-09 11:43:03 +00:00
// Return data to server-render them
return data
})
2017-05-04 07:57:10 +00:00
}))
2017-07-09 11:43:03 +00:00
2017-05-04 07:57:10 +00:00
// If no Components found, returns 404
if (!Components.length) {
context.nuxt.error = context.error({ statusCode: 404, message: 'This page could not be found.' })
}
2017-07-09 11:43:03 +00:00
<% if (isDev) { %>if (asyncDatas.length) debug('Data fetching ' + context.url + ': ' + (Date.now() - s) + 'ms')<% } %>
2017-05-04 07:57:10 +00:00
// datas are the first row of each
2017-07-09 11:43:03 +00:00
context.nuxt.data = asyncDatas.map(r => r[0] || {})
2017-05-04 07:57:10 +00:00
// If an error occured in the execution
if (_app.$options._nuxt.err) {
context.nuxt.error = _app.$options._nuxt.err
2017-05-04 07:57:10 +00:00
}
2017-07-09 11:43:03 +00:00
<% if (store) { %>
// Add the state from the vuex store
context.nuxt.state = store.state
<% } %>
2017-05-04 07:57:10 +00:00
// If no error, return main app
if (!context.nuxt.error) {
2016-11-07 01:34:58 +00:00
return _app
2017-05-04 07:57:10 +00:00
}
2017-07-09 11:43:03 +00:00
2017-05-04 07:57:10 +00:00
// Load layout for error page
layout = (typeof NuxtError.layout === 'function' ? NuxtError.layout(ctx) : NuxtError.layout)
context.nuxt.layout = layout || ''
await _app.loadLayout(layout)
_app.setLayout(layout)
2017-07-09 11:43:03 +00:00
2017-05-04 07:57:10 +00:00
return _app
2016-11-07 01:34:58 +00:00
}
function sanitizeDynamicComponents(components) {
Object.keys(components).forEach((name) => {
const component = components[name]
// Remove SSR register hookd
if (Array.isArray(component.beforeCreate)) {
component.beforeCreate = component.beforeCreate.filter((fn) => fn !== component._ssrRegister)
if (!component.beforeCreate.length) delete component.beforeCreate
}
// Remove SSR & informations properties
delete component._ssrRegister
delete component.__file
if (component.staticRenderFns && !component.staticRenderFns.length) {
delete component.staticRenderFns
}
// Add Component to NUXT.components[i][name]
components[name] = component
})
return clone(components)
2017-07-07 13:44:04 +00:00
}