Nuxt/packages/vue-app/template/server.js

270 lines
8.7 KiB
JavaScript
Raw Normal View History

2016-11-10 23:01:36 +00:00
import { stringify } from 'querystring'
2018-10-24 13:46:06 +00:00
import Vue from 'vue'
<% if (fetch.server) { %>import fetch from 'node-fetch'<% } %>
<% if (features.middleware) { %>import middleware from './middleware.js'<% } %>
import {
<% if (features.asyncData) { %>applyAsyncData,<% } %>
<% if (features.middleware) { %>middlewareSeries,<% } %>
getMatchedComponents,
promisify,
sanitizeComponent
} from './utils.js'
import { createApp, NuxtError } from './index.js'
2019-01-06 07:56:59 +00:00
import NuxtLink from './components/nuxt-link.server.js' // should be included after ./index.js
// Component: <NuxtLink>
Vue.component(NuxtLink.name, NuxtLink)
<% if (features.componentAliases) { %>Vue.component('NLink', NuxtLink)<% } %>
2017-07-09 11:43:03 +00:00
<% if (fetch.server) { %>if (!global.fetch) { global.fetch = fetch }<% } %>
2018-10-24 13:46:06 +00:00
const noopApp = () => new Vue({ render: h => h('div') })
2017-07-09 11:43:03 +00:00
function urlJoin() {
return Array.prototype.slice.call(arguments).join('/').replace(/\/+/g, '/')
}
2018-10-24 13:46:06 +00:00
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 : '')
2018-10-24 13:46:06 +00:00
const routerBase = '<%= router.base %>'
if (!opts.path.startsWith('http') && (routerBase !== '/' && !opts.path.startsWith(routerBase))) {
opts.path = urlJoin(routerBase, opts.path)
2017-07-09 11:43:03 +00:00
}
// 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{{globals.context}}, defaults to window.__NUXT__)
ssrContext.nuxt = { <% if (features.layouts) { %>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
<% if (features.meta) { %>
// Add meta infos (used in renderer.js)
ssrContext.meta = _app.$meta()
<% } %>
<% if (features.asyncData) { %>
// Keep asyncData for each matched component in ssrContext (used in app/utils.js via this.$ssrContext)
ssrContext.asyncData = {}
<% } %>
const beforeRender = async () => {
// Call beforeNuxtRender() methods
2018-10-24 13:46:06 +00:00
await Promise.all(ssrContext.beforeRenderFns.map(fn => promisify(fn, { Components, nuxtState: ssrContext.nuxt })))
<% if (store) { %>
ssrContext.rendered = () => {
// Add the state from the vuex store
ssrContext.nuxt.state = store.state
}
<% } %>
}
const renderErrorPage = async () => {
<% if (features.layouts) { %>
// Load layout for error page
2018-10-24 13:46:06 +00:00
const 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 (debug) { %>const s = 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) {
console.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
<% if (features.middleware) { %>
/*
** Call global middleware (nuxt.config.js)
*/
2018-10-24 13:46:06 +00:00
let midd = <%= serialize(router.middleware).replace('middleware(', 'function(') %><%= isTest ? '// eslint-disable-line' : '' %>
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()
<% } %>
<% if (features.layouts) { %>
/*
** 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)
ssrContext.nuxt.layout = _app.layoutName
<% } %>
2017-07-27 14:26:59 +00:00
<% if (features.middleware) { %>
/*
** Call middleware (layout + pages)
*/
midd = []
<% if (features.layouts) { %>
layout = sanitizeComponent(layout)
if (layout.options.middleware) {
midd = midd.concat(layout.options.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()
<% } %>
<% if (features.validate) { %>
/*
** Call .validate()
*/
2017-05-04 07:57:10 +00:00
let isValid = true
2018-08-25 09:42:00 +00:00
try {
for (const Component of Components) {
if (typeof Component.options.validate !== 'function') {
continue
}
isValid = await Component.options.validate(app.context)
if (!isValid) {
break
}
}
} catch (validationError) {
// ...If .validate() threw an error
app.context.error({
statusCode: validationError.statusCode || '500',
message: validationError.message
})
return renderErrorPage()
}
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()
<% if (features.asyncData || features.fetch) { %>
2017-05-04 07:57:10 +00:00
// Call asyncData & fetch hooks on components matched by the route.
2018-10-24 13:46:06 +00:00
const asyncDatas = await Promise.all(Components.map((Component) => {
const promises = []
2017-07-27 14:26:59 +00:00
<% if (features.asyncData) { %>
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') {
2018-10-24 13:46:06 +00:00
const 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)
}
<% } %>
2017-07-09 11:43:03 +00:00
<% if (features.fetch) { %>
// Call fetch(context)
2017-07-09 11:43:03 +00:00
if (Component.options.fetch) {
promises.push(Component.options.fetch(app.context))
2018-10-24 13:46:06 +00:00
} else {
2017-07-09 11:43:03 +00:00
promises.push(null)
}
<% } %>
2017-07-09 11:43:03 +00:00
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 (debug) { %>if (process.env.DEBUG && asyncDatas.length)console.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
}