异步/等待不适用于中间件nodejs

时间:2017-09-23 06:54:11

标签: node.js session async-await middleware es6-promise

我创建了一个中间件来为每个使用token和userId参数的登录创建一个会话,它基于环回框架。

  • 首先检查具有相同userID和tokenID的会话是否存在,然后在此阶段创建新的会话转义,否则创建会话。

这是我的代码:

module.exports = async function(req, res, next) {
  try {

    let jobUser = req.app.models.JobsUser;

    var session = req.app.models.userSession;
    var sessionRequest = req.app.models.UserSessionRequest;
    var ip = req.headers["x-forwarded-for"] || req.connection.remoteAddress;
    let logDetails = {
      lastActivity: new Date(),
      updatedAt: new Date(),
      ip: ip,
      browser: req.useragent.browser,
      browserVersion: req.useragent.version,
      platform: req.useragent.platform,
      operatingSystem: req.useragent.os,
      block: false,
      blockBy: "",
    };
    /** Create session after login */
    await jobUser.afterRemote('login', async(context, user, next) => {


      /** Check if already a session exist for this user.*/
      let newSession = session.find({ where: { userId: user.userId, token: user.id } }, (err, result) => {
        if (err) {
          console.log('Records already exist');
          next(err);
          return;
        }
        console.log('AccessToken: ' + result.length);
        console.log('AccessToken: ' + user.id);
        console.log('Session does not exist');
        if (result.length === 0) {
          let uer = { toke: user.id, userId: user.userId, createdAt: user.created };
          let rec = {...logDetails, ...uer };
          session.create(rec, (err, result) => {
            next();
            return;
          });
        }
      });
    });

    if (req.accessToken === null) return next();

    let logs = {...logDetails, userId: req.accessToken.userId, token: req.accessToken.id, createdAt: req.accessToken.created }
      /** Update session for every other request */
    let result = await session.updateAll({ userId: req.accessToken.userId, token: req.accessToken.id }, logs);
    var requestDetails = {
      sessionId: result.id,
      createdAt: new Date(),
      updatedAt: new Date(),
      route: req.headers.referer,
      method: req.method,
      browser: req.useragent.browser,
      platform: req.useragent.platform,
      operatingSystem: req.useragent.os
    };
    if (result) {
      await sessionRequest.create(requestDetails);
    }

    /** Close session after logout */
    jobUser.afterRemote('logout', (context, User, next) => {
      session.updateAll({ userId: req.accessToken.userId, token: req.accessToken.id }, { closedAt: new Date() });
      next();
      return;
    });

    next();
    return;
  } catch (err) {
    next(err);
    return;
  }
};

输出:

enter image description here

为此,我使用 async / await 来不同时创建多个会话。

我不知道我的方法是错误的,还是 async / wait 无法正常使用中间件。

你的建议会很感激。

注意:其基于API的环回和角度4

0 个答案:

没有答案