entry-server.js 2.03 KB
import {createApp} from './app';
import _ from 'lodash/core';
import {
    SET_ENV,
    INIT_ROUTE_CHANGE
} from 'store/yoho/types';

export default context => {
    return new Promise((resolve, reject) => {
        const {app, router, store} = createApp(context);
        const {url} = context;

        const route = router.resolve(url).route;

        // if (url !== route.fullPath) {
        //     return reject({code: 500, message: 'url not matched', url: route.fullPath});
        // }
        store.commit(SET_ENV, context.env);
        router.push(url);
        router.onReady(() => {
            try {
                const matched = router.getMatchedComponents();

                if (!matched.length) {
                    reject({code: 404});
                }
                const routes = [];
                const rootRoute = _.find(router.options.routes, r => r.meta && r.meta.root);

                if (rootRoute) {
                    routes.push({
                        name: rootRoute.name,
                        fullPath: rootRoute.path
                    });
                }

                if (route.name !== 'channel.home') {
                    routes.push({
                        name: route.name,
                        fullPath: route.fullPath
                    });
                }

                store.commit(INIT_ROUTE_CHANGE, {routes});
                Promise.all(matched.map(({asyncData}) =>
                    asyncData && asyncData({store, router: router.currentRoute})))
                    .then(() => {
                        context.state = store.state;
                        resolve(app);
                    }).catch((e) => {
                        reject({
                            code: 500,
                            message: e.stack || e.toString()
                        });
                    });
            } catch (e) {
                reject({
                    code: 500,
                    message: e.stack || e.toString()
                });
            }
        }, reject);
    });
};