浅谈在koa2中实现页面渲染的全局数据

最近用koa2做一个项目的web端,遇到一个场景。

该项目主要用的是传统的服务端渲染的方式,所以会用 koa-views 去做页面的渲染工作。实现方式就是 ctx.render('path',data),那么,有如下场景,每个页面都需要去验证是否登录,登录了要返回页面个人数据,这个情况,怎么办呢?我不想每次都去手动的加入个人数据啊。例如这样:

let data = {
      "user":"12",
      "questionList":questionList
    };
    await ctx.render("index",data);

此处的user就是每个页面都是要返回的数据。

很显然,每个页面都要获得的数据,用中间件去获取,类似java的拦截器,过滤器之类的了。

import {UserClient} from "../manager/user/UserClient";
export const signInStatusMiddleware = async (ctx:any,next:any)=>{
  console.log("signInStatusMiddleware")
  let accessToken = ctx.cookies.get("ACCESS-TOKEN");
  if(accessToken){
    let userClient :UserClient = new UserClient;
    let user = await userClient.getUserByToken(accessToken);
  }
  await next();
}

OK,中间件中已经拿到了用户数据了,那么,问题来了。数据是可以拿,怎么放呢?

找到koa-views 源码。有如下代码:

return function views(ctx, next) {
  if (ctx.render) return next()

  ctx.render = function(relPath, locals = {}) {
   return getPaths(path, relPath, extension).then(paths => {
    const suffix = paths.ext
    const state = Object.assign(locals, options, ctx.state || {})
    // deep copy partials
    state.partials = Object.assign({}, options.partials || {})
    debug('render `%s` with %j', paths.rel, state)
    ctx.type = 'text/html'

    if (isHtml(suffix) && !map) {
     return send(ctx, paths.rel, {
      root: path
     })
    } else {
     const engineName = map && map[suffix] ? map[suffix] : suffix

     const render = engineSource[engineName]

     if (!engineName || !render)
      return Promise.reject(
       new Error(`Engine not found for the ".${suffix}" file extension`)
      )

     return render(resolve(path, paths.rel), state).then(html => {
      ctx.body = html
     })
    }
   })
  }

  return next()
 }

关键是这一段

const state = Object.assign(locals, options, ctx.state || {})

很显然,state 是将传入的数据,合并了,中间件配置的options ,和ctx.state的。中间件显式配置显然部合适,所以,做法是,在拦截器中间件中,把user赋值给ctx.state.

export const signInStatusMiddleware = async (ctx:any,next:any)=>{
  console.log("signInStatusMiddleware")
  let accessToken = ctx.cookies.get("ACCESS-TOKEN");
  if(accessToken){
    let userClient :UserClient = new UserClient;
    let user = await userClient.getUserByToken(accessToken);
    ctx.state = Object.assign(ctx.state,{"user":user});
  }
  await next();
}
      

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/5192.html