entry-server.js 1.31 KB
import {createApp} from './app';
import createReport from 'report-error';

import {
  SET_ENV,
} from 'store/yoho/types';


export default context => {
  const reportError = createReport(context);

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

    store.commit(SET_ENV, {context});
    router.push(url);
    router.onReady(() => {
      const matched = router.getMatchedComponents();

      if (matched.some(m => !m)) {
        reportError(new Error('导航组件为空'));
        router.push({name: 'error.500'});
        return resolve(app);
      }
      if (!matched.length) {
        return reject({code: 404, message: ''});
      }
      const asyncDataPromises = matched.map(({asyncData}) => {
        try {
          return asyncData && asyncData({store, router: router.currentRoute});
        } catch (error) {
          return Promise.reject(error);
        }
      }).filter(p => p);

      Promise.all(asyncDataPromises)
        .then(() => {
          context.state = store.state;
          return resolve(app);
        }).catch(e => {
          reportError(e);
          return resolve(app);
        });
    });

    router.onError(e => {
      reportError(e);
      router.push({name: 'error.500'});
      return resolve(app);
    });
  });
};