使用AWS Lambda(TypeError)的Express函数中的异步中间件

时间:2019-07-07 08:23:07

标签: node.js express aws-lambda middleware aws-serverless

我想在中间件中使用一个async函数,该函数将用户提取到我的AWS Lambda函数中。

代码如下:

const bodyParser = require('body-parser');
const awsServerlessExpressMiddleware = require('aws-serverless-express/middleware');
const AWS = require('aws-sdk');

const asyncHandler = fn => (req, res, next) =>
  Promise.resolve(fn(req, res, next)).catch(next);

const pipe = (...fns) => x => fns.reduce((y, f) => f(y), x);
const tapRoute = f => route => {
  route.use(f);
  return route;
};

const configureCors = route => {
  route.use(function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header(
      'Access-Control-Allow-Headers',
      'Origin, X-Requested-With, Content-Type, Accept'
    );
    next();
  });
};
const injectUser = route => {
  route.use(async function(req, res, next) {
    try {
      const IDP_REGEX = /.*\/.*,(.*)\/(.*):CognitoSignIn:(.*)/;
      const authProvider =
        req.apiGateway.event.requestContext.identity
          .cognitoAuthenticationProvider;
      const [, , , userId] = authProvider.match(IDP_REGEX);
      console.log(userId);
      console.log('Got user id');

      const cognito = new AWS.CognitoIdentityServiceProvider();
      const listUsersResponse = await cognito
        .listUsers({
          UserPoolId: process.env.AUTH_LAMBDAUSERB2E6BC69_USERPOOLID,
          Filter: `sub = "${userId}"`,
          Limit: 1,
        })
        .promise();
      console.log('ListedUsers');
      const user = listUsersResponse.Users[0];
      req.user = user;
      next();
    } catch (error) {
      console.log(error);
      next(error);
    } finally {
      return route;
    }
  });
};

const applyMiddleware = (route, ...middleware) =>
  pipe(
    tapRoute(bodyParser.json()),
    tapRoute(awsServerlessExpressMiddleware.eventContext()),
    configureCors,
    injectUser,
    ...middleware
  )(route);

module.exports = {
  applyMiddleware,
};

代码在此行中引发错误:

route.use(async function(req, res, next) {

这是错误:

module initialization error: TypeError
at injectUser (/var/task/middleware.js:25:9)
at fns.reduce (/var/task/middleware.js:8:52)
at Array.reduce (<anonymous>)
at x (/var/task/middleware.js:8:35)
at applyMiddleware (/var/task/middleware.js:63:4)
at Object.<anonymous> (/var/task/app.js:13:1)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)

通常,以后我会像这样使用这种中间件:

const express = require('express');
const applyMiddleware = require('./middleware').applyMiddleware;

const app = express();
applyMiddleware(app);

app.get( // ... rest of the code

但是有时我也会按路线注入中间件。

这是怎么回事?为什么会引发此TypeError?有什么方法可以使用将用户注入管道的异步中间件,从而减少样板?如果我将injectUser注释掉,则中间件可以工作...

编辑:

使用app.use(async function // ...可以正常工作,但是我想在pipe中也使用异步功能。在applyMiddleware中。

1 个答案:

答案 0 :(得分:1)

问题是您的configureCors函数。您在那里没有返回任何内容,因此链断了,injectUser得到了undefined route变量。应该像下面这样更新

const configureCors = route => {
  route.use(function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header(
      'Access-Control-Allow-Headers',
      'Origin, X-Requested-With, Content-Type, Accept'
    );
    next();

  });
  return route;
};