Nuxt/lib/app/server.js

228 lines
7.7 KiB
JavaScript
Raw Normal View History

'use strict'
2016-11-07 01:34:58 +00:00
const debug = require('debug')('nuxt:render')
2016-12-15 17:48:31 +00:00
debug.color = 4 // force blue color
2016-11-07 01:34:58 +00:00
import Vue from 'vue'
2017-02-28 12:10:58 +00:00
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-04-14 14:31:14 +00:00
import { applyAsyncData, getMatchedComponents, getContext, promiseSeries, promisify, urlJoin } from './utils'
2016-11-07 01:34:58 +00:00
const isDev = <%= isDev %>
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 context => {
2017-05-02 06:57:39 +00:00
const { app, router<%= (store ? ', store' : '') %> } = createApp(context)
const _app = new Vue(app)
// Add store to the context
<%= (store ? 'context.store = store' : '') %>
// Nuxt object
2017-03-25 17:59:46 +00:00
context.nuxt = { layout: 'default', data: [], error: null<%= (store ? ', state: null' : '') %>, serverRendered: true }
2016-11-10 23:01:36 +00:00
// create context.next for simulate next() of beforeEach() when wanted to redirect
context.redirected = false
context.next = function (opts) {
2017-02-22 18:19:17 +00:00
context.redirected = opts
2017-02-07 09:46:05 +00:00
// if nuxt generate
2016-11-10 23:01:36 +00:00
if (!context.res) {
context.nuxt.serverRendered = false
2016-11-10 23:01:36 +00:00
return
}
opts.query = stringify(opts.query)
opts.path = opts.path + (opts.query ? '?' + opts.query : '')
opts.path = urlJoin('<%= router.base %>', opts.path)
context.res.writeHead(opts.status, {
'Location': opts.path
2016-11-10 23:01:36 +00:00
})
context.res.end()
}
2016-11-07 01:34:58 +00:00
// Add meta infos
context.meta = _app.$meta()
// Error function
context.error = _app.$options._nuxt.error.bind(_app)
2016-11-07 01:34:58 +00:00
<%= (isDev ? 'const s = isDev && Date.now()' : '') %>
let ctx = null
let componentsLoaded = false
2017-03-22 14:47:34 +00:00
let Components = []
2017-03-24 00:28:19 +00:00
let promises = getMatchedComponents(router.match(context.url)).map((Component) => {
return new Promise((resolve, reject) => {
const _resolve = (Component) => {
if (!Component.options) {
Component = Vue.extend(Component) // fix issue #6
Component._Ctor = Component
} else {
Component._Ctor = Component
Component.extendOptions = Component.options
}
2017-03-26 21:38:51 +00:00
// For debugging purpose
if (!Component.options.name && Component.options.__file) {
Component.options.name = Component.options.__file
}
2017-03-24 00:28:19 +00:00
resolve(Component)
}
Component().then(_resolve).catch(reject)
})
2017-03-22 14:47:34 +00:00
})
2017-03-24 00:28:19 +00:00
return Promise.all(promises)
.then((_Components) => {
componentsLoaded = true
2017-03-24 00:28:19 +00:00
Components = _Components
// set router's location
return new Promise((resolve) => {
router.push(context.url, resolve)
})
})
.then(() => {
// Add route to the context
context.route = router.currentRoute
// Update context
2017-05-14 21:56:00 +00:00
ctx = getContext(context, app)
2017-03-22 14:47:34 +00:00
// nuxtServerInit
<% if (store) { %>
2017-05-14 21:56:00 +00:00
let promise = (store._actions && store._actions.nuxtServerInit ? store.dispatch('nuxtServerInit', omit(getContext(context, app), 'redirect', 'error')) : null)
if (!promise || (!(promise instanceof Promise) && (typeof promise.then !== 'function'))) promise = Promise.resolve()
2017-03-22 14:47:34 +00:00
<% } else { %>
let promise = Promise.resolve()
<% } %>
return promise
})
2016-11-17 12:52:00 +00:00
.then(() => {
2016-12-12 15:30:07 +00:00
// Sanitize Components
Components = Components.map((Component) => {
2016-11-17 12:52:00 +00:00
let promises = []
if (!Component.options) {
Component = Vue.extend(Component)
Component._Ctor = Component
2016-11-18 13:45:25 +00:00
} else {
Component._Ctor = Component
Component.extendOptions = Component.options
2016-11-17 12:52:00 +00:00
}
2016-12-12 15:30:07 +00:00
return Component
})
2017-03-17 17:02:58 +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]
})
if (context.nuxt.error) return
return promiseSeries(midd, ctx)
})
.then(() => {
2016-12-24 00:55:32 +00:00
// Set layout
2017-03-17 17:02:58 +00:00
let layout = Components.length ? Components[0].options.layout : NuxtError.layout
if (typeof layout === 'function') {
layout = layout(ctx)
}
2017-03-22 14:47:34 +00:00
return _app.loadLayout(layout).then(() => _app.setLayout(layout))
2016-12-24 11:34:41 +00:00
})
2017-02-03 14:09:27 +00:00
.then((layout) => {
2017-03-25 17:59:46 +00:00
// Set layout to __NUXT__
context.nuxt.layout = _app.layoutName
2017-03-17 17:02:58 +00:00
// Call middleware (layout + pages)
let midd = []
2017-02-03 14:09:27 +00:00
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]
})
if (context.nuxt.error) return
return promiseSeries(midd, ctx)
})
2016-12-24 11:34:41 +00:00
.then(() => {
2016-12-12 15:30:07 +00:00
// Call .validate()
2016-12-20 17:05:27 +00:00
let isValid = true
Components.forEach((Component) => {
if (!isValid) return
if (typeof Component.options.validate !== 'function') return
isValid = Component.options.validate({
2017-04-05 16:25:35 +00:00
params: context.route.params || {},
2017-04-05 19:33:11 +00:00
query: context.route.query || {}<%= (store ? ', store: ctx.store' : '') %>
2016-12-12 15:30:07 +00:00
})
})
if (!isValid) {
2016-12-21 14:03:23 +00:00
// Don't server-render the page in generate mode
if (context._generate) {
context.nuxt.serverRendered = false
}
2016-12-12 15:30:07 +00:00
// Call the 404 error by making the Components array empty
Components = []
return _app
}
2017-02-28 12:10:58 +00:00
// Call asyncData & fetch hooks on components matched by the route.
2016-12-12 15:30:07 +00:00
return Promise.all(Components.map((Component) => {
let promises = []
2017-02-28 12:10:58 +00:00
if (Component.options.asyncData && typeof Component.options.asyncData === 'function') {
let promise = promisify(Component.options.asyncData, ctx)
// Call asyncData(context)
promise.then((asyncDataResult) => {
2017-04-14 14:31:14 +00:00
applyAsyncData(Component, asyncDataResult)
return asyncDataResult
2016-11-17 12:52:00 +00:00
})
promises.push(promise)
2017-03-02 16:31:37 +00:00
} else {
promises.push(null)
2016-11-17 12:52:00 +00:00
}
if (Component.options.fetch) {
promises.push(Component.options.fetch(ctx))
2017-03-02 16:31:37 +00:00
} else {
promises.push(null)
2016-11-17 12:52:00 +00:00
}
return Promise.all(promises)
}))
})
2017-03-02 16:31:37 +00:00
.then((res) => {
if (!Components.length) {
2017-02-03 14:09:27 +00:00
context.nuxt.error = context.error({ statusCode: 404, message: 'This page could not be found.' })
<%= (store ? 'context.nuxt.state = store.state' : '') %>
return _app
}
2016-11-07 01:34:58 +00:00
<% if (isDev) { %>
2017-03-24 12:52:15 +00:00
debug('Data fetching ' + context.url + ': ' + (Date.now() - s) + 'ms')
2016-11-07 01:34:58 +00:00
<% } %>
// datas are the first row of each
2017-03-02 16:31:37 +00:00
context.nuxt.data = res.map((r) => (r[0] || {}))
context.nuxt.error = _app.$options._nuxt.err
2016-11-07 01:34:58 +00:00
<%= (store ? '// Add the state from the vuex store' : '') %>
<%= (store ? 'context.nuxt.state = store.state' : '') %>
2017-03-25 17:59:46 +00:00
// If no error, return main app
if (!context.nuxt.error) {
return _app
}
// Load layout for error page
let layout = (typeof NuxtError.layout === 'function' ? NuxtError.layout(ctx) : NuxtError.layout)
context.nuxt.layout = layout || ''
return _app.loadLayout(layout)
.then(() => _app.setLayout(layout))
.then(() => _app)
2016-11-07 01:34:58 +00:00
})
.catch(function (error) {
2017-04-14 09:57:08 +00:00
if (error instanceof Error || error.constructor.toString().indexOf('Error()') !== -1) {
2017-03-24 00:28:19 +00:00
return Promise.reject(error)
2016-12-21 14:03:23 +00:00
}
2017-04-14 09:57:08 +00:00
if (typeof error === 'string') {
error = { statusCode: 500, message: error }
}
context.nuxt.error = context.error(error)
2016-11-07 01:34:58 +00:00
<%= (store ? 'context.nuxt.state = store.state' : '') %>
return _app
})
}