Refacto client app

This commit is contained in:
Sébastien Chopin 2017-10-16 10:40:08 +02:00
parent 7534001123
commit df2af66355

View File

@ -4,10 +4,11 @@ import { createApp, NuxtError } from './index'
import { import {
applyAsyncData, applyAsyncData,
sanitizeComponent, sanitizeComponent,
resolveRouteComponents,
getMatchedComponents, getMatchedComponents,
getMatchedComponentsInstances, getMatchedComponentsInstances,
flatMapComponents, flatMapComponents,
getContext, setContext,
middlewareSeries, middlewareSeries,
promisify, promisify,
getLocation, getLocation,
@ -96,40 +97,25 @@ function mapTransitions(Components, to, from) {
} }
async function loadAsyncComponents (to, from, next) { async function loadAsyncComponents (to, from, next) {
// Check if route hash changed // Check if route hash changed (this._hashChanged)
const fromPath = from.fullPath.split('#')[0] const fromPath = from.fullPath.split('#')[0]
const toPath = to.fullPath.split('#')[0] const toPath = to.fullPath.split('#')[0]
this._hashChanged = fromPath === toPath this._hashChanged = fromPath === toPath
<% if (loading) { %> <% if (loading) { %>
if (!this._hashChanged && this.$loading.start) { if (!this._hashChanged && this.$loading.start) {
this.$loading.start() this.$loading.start()
} }
<% } %> <% } %>
try { try {
await Promise.all(flatMapComponents(to, (Component, _, match, key) => { await resolveRouteComponents(to)
// If component already resolved
if (typeof Component !== 'function' || Component.options) {
const _Component = sanitizeComponent(Component)
match.components[key] = _Component
return _Component
}
// Resolve component
return Component().then(Component => {
const _Component = sanitizeComponent(Component)
match.components[key] = _Component
return _Component
})
}))
next() next()
} catch (err) { } catch (err) {
if (!err) err = {} err = err || {}
const statusCode = err.statusCode || err.status || (err.response && err.response.status) || 500 const statusCode = err.statusCode || err.status || (err.response && err.response.status) || 500
this.error({ statusCode, message: err.message }) this.error({ statusCode, message: err.message })
next(false) next(false)
} }
} }
@ -145,20 +131,15 @@ function applySSRData(Component, ssrData) {
function resolveComponents(router) { function resolveComponents(router) {
const path = getLocation(router.options.base, router.options.mode) const path = getLocation(router.options.base, router.options.mode)
return flatMapComponents(router.match(path), (Component, _, match, key, index) => { return flatMapComponents(router.match(path), async (Component, _, match, key, index) => {
// If component already resolved // If component is not resolved yet, resolve it
if (typeof Component !== 'function' || Component.options) { if (typeof Component === 'function' && !Component.options) {
const _Component = applySSRData(sanitizeComponent(Component), NUXT.data ? NUXT.data[index] : null) Component = await Component()
match.components[key] = _Component
return _Component
} }
// Sanitize it and save it
// Resolve component const _Component = applySSRData(sanitizeComponent(Component), NUXT.data ? NUXT.data[index] : null)
return Component().then(Component => { match.components[key] = _Component
const _Component = applySSRData(sanitizeComponent(Component), NUXT.data ? NUXT.data[index] : null) return _Component
match.components[key] = _Component
return _Component
})
}) })
} }
@ -204,17 +185,13 @@ async function render (to, from, next) {
} }
// Update context // Update context
const context = getContext({ setContext(app, {
to, route: to,
from, from,
<% if (store) { %>store,<% } %> next: _next.bind(this)
isClient: true, })
next: _next.bind(this), this._dateLastError = app.nuxt.dateErr
error: this.error.bind(this) this._hadError = !!app.nuxt.err
}, app)
this._context = context
this._dateLastError = this.$options._nuxt.dateErr
this._hadError = !!this.$options._nuxt.err
// Get route's matched components // Get route's matched components
const Components = getMatchedComponents(to) const Components = getMatchedComponents(to)
@ -222,15 +199,14 @@ async function render (to, from, next) {
// If no Components matched, generate 404 // If no Components matched, generate 404
if (!Components.length) { if (!Components.length) {
// Default layout // Default layout
await callMiddleware.call(this, Components, context) await callMiddleware.call(this, Components, app.context)
if (context._redirected) return if (app.context._redirected) return
// Load layout for error page // Load layout for error page
const layout = await this.loadLayout(typeof NuxtError.layout === 'function' ? NuxtError.layout(context) : NuxtError.layout) const layout = await this.loadLayout(typeof NuxtError.layout === 'function' ? NuxtError.layout(app.context) : NuxtError.layout)
await callMiddleware.call(this, Components, context, layout) await callMiddleware.call(this, Components, context, layout)
if (context._redirected) return if (context._redirected) return
// Show error page
this.error({ statusCode: 404, message: '<%= messages.error_404 %>' }) app.context.error({ statusCode: 404, message: '<%= messages.error_404 %>' })
return next() return next()
} }
@ -247,19 +223,19 @@ async function render (to, from, next) {
try { try {
// Call middleware // Call middleware
await callMiddleware.call(this, Components, context) await callMiddleware.call(this, Components, app.context)
if (context._redirected) return if (app.context._redirected) return
// Set layout // Set layout
let layout = Components[0].options.layout let layout = Components[0].options.layout
if (typeof layout === 'function') { if (typeof layout === 'function') {
layout = layout(context) layout = layout(app.context)
} }
layout = await this.loadLayout(layout) layout = await this.loadLayout(layout)
// Call middleware for layout // Call middleware for layout
await callMiddleware.call(this, Components, context, layout) await callMiddleware.call(this, Components, app.context, layout)
if (context._redirected) return if (app.context._redirected) return
// Call .validate() // Call .validate()
let isValid = true let isValid = true
@ -269,7 +245,7 @@ async function render (to, from, next) {
isValid = Component.options.validate({ isValid = Component.options.validate({
params: to.params || {}, params: to.params || {},
query : to.query || {}, query : to.query || {},
<% if(store) { %>store: context.store <% } %> <% if(store) { %>store<% } %>
}) })
}) })
// ...If .validate() returned false // ...If .validate() returned false
@ -294,7 +270,7 @@ async function render (to, from, next) {
// Call asyncData(context) // Call asyncData(context)
if (hasAsyncData) { if (hasAsyncData) {
const promise = promisify(Component.options.asyncData, context) const promise = promisify(Component.options.asyncData, app.context)
.then(asyncDataResult => { .then(asyncDataResult => {
applyAsyncData(Component, asyncDataResult) applyAsyncData(Component, asyncDataResult)
<% if(loading) { %>if(this.$loading.increase) this.$loading.increase(loadingIncrease)<% } %> <% if(loading) { %>if(this.$loading.increase) this.$loading.increase(loadingIncrease)<% } %>
@ -304,7 +280,7 @@ async function render (to, from, next) {
// Call fetch(context) // Call fetch(context)
if (hasFetch) { if (hasFetch) {
let p = Component.options.fetch(context) let p = Component.options.fetch(app.context)
if (!p || (!(p instanceof Promise) && (typeof p.then !== 'function'))) { if (!p || (!(p instanceof Promise) && (typeof p.then !== 'function'))) {
p = Promise.resolve(p) p = Promise.resolve(p)
} }
@ -332,7 +308,7 @@ async function render (to, from, next) {
// Load error layout // Load error layout
let layout = NuxtError.layout let layout = NuxtError.layout
if (typeof layout === 'function') { if (typeof layout === 'function') {
layout = layout(context) layout = layout(app.context)
} }
await this.loadLayout(layout) await this.loadLayout(layout)
@ -376,14 +352,14 @@ function fixPrepatch (to, ___) {
}) })
// Hide error component if no error // Hide error component if no error
if (this._hadError && this._dateLastError === this.$options._nuxt.dateErr) { if (this._hadError && this._dateLastError === this.$options.nuxt.dateErr) {
this.error() this.error()
} }
// Set layout // Set layout
let layout = this.$options._nuxt.err ? NuxtError.layout : to.matched[0].components.default.options.layout let layout = this.$options.nuxt.err ? NuxtError.layout : to.matched[0].components.default.options.layout
if (typeof layout === 'function') { if (typeof layout === 'function') {
layout = layout(this._context) layout = layout(app.context)
} }
this.setLayout(layout) this.setLayout(layout)
@ -459,9 +435,13 @@ function addHotReload ($component, depth) {
<%= (loading ? 'this.$loading.finish && this.$loading.finish()' : '') %> <%= (loading ? 'this.$loading.finish && this.$loading.finish()' : '') %>
router.push(path) router.push(path)
} }
let context = getContext({ route: router.currentRoute<%= (store ? ', store' : '') %>, isClient: true, isHMR: true, next: next.bind(this), error: this.error }, app) setContext(app, {
route: router.currentRoute,
isHMR: true,
next: next.bind(this)
})
<%= (loading ? 'this.$loading.start && this.$loading.start()' : '') %> <%= (loading ? 'this.$loading.start && this.$loading.start()' : '') %>
callMiddleware.call(this, Components, context) callMiddleware.call(this, Components, app.context)
.then(() => { .then(() => {
// If layout changed // If layout changed
if (depth !== 0) return Promise.resolve() if (depth !== 0) return Promise.resolve()
@ -538,7 +518,7 @@ async function mountApp(__app) {
} }
// Enable transitions // Enable transitions
_app.setTransitions = _app.$options._nuxt.setTransitions.bind(_app) _app.setTransitions = _app.$options.nuxt.setTransitions.bind(_app)
if (Components.length) { if (Components.length) {
_app.setTransitions(mapTransitions(Components, router.currentRoute)) _app.setTransitions(mapTransitions(Components, router.currentRoute))
_lastPaths = router.currentRoute.matched.map(route => compile(route.path)(router.currentRoute.params)) _lastPaths = router.currentRoute.matched.map(route => compile(route.path)(router.currentRoute.params))
@ -546,7 +526,6 @@ async function mountApp(__app) {
} }
// Initialize error handler // Initialize error handler
_app.error = _app.$options._nuxt.error.bind(_app)
_app.$loading = {} // To avoid error while _app.$nuxt does not exist _app.$loading = {} // To avoid error while _app.$nuxt does not exist
if (NUXT.error) _app.error(NUXT.error) if (NUXT.error) _app.error(NUXT.error)