Middy: Strange behaviour of async middlewares (maybe need docs)

Created on 19 Jan 2019  路  4Comments  路  Source: middyjs/middy

Hi!
Yesterday we got next error (maybe bug - I don't know).
If we call next() in the async middleware, our handler run twice.
It's fully my bad, and I don't know what it exactly, but I think it will be great to mention this in docs.

Most helpful comment

UPDATE [SOLVED]:
Looks like we needed to read the docs closer.
With async middleware... you need to either return the promise OR in the case of async/await just return.

We we're unfortunately return next() which I can see now would call twice.

All 4 comments

We're seeing two calls as well. In our case, not sure how this is possible when each call should in the end call the Lambda callback which should kill the function.

This is what our usage looks like...

'use strict';

const middy = require('middy');
const reroute = require('middy-reroute');

const handler = middy((event, context, cb) => {
  const request = event.Records ? event.Records[0].cf.request : event;
  console.log({ test: !!event.Records, event: JSON.stringify(event) });
  console.log({ request: JSON.stringify(request) });
  cb(null, request);
}).use(reroute());

module.exports = { handler };

those consoles are logging out twice each.

UPDATE [SOLVED]:
Looks like we needed to read the docs closer.
With async middleware... you need to either return the promise OR in the case of async/await just return.

We we're unfortunately return next() which I can see now would call twice.

@iDVB The same situation. I think this text should be camel case, in red color =)

@iDVB partly solved my issue when using async you can just return in your middleware before after async functions, no need for next().

I had to switch from middy:0.25.0 to @middy/core:1.0.0-alpha.29 to ultimately solve my issue. Which is the way the handler functions are being invoked only in my tests and not in production.

const viaHandler = async (event, functionName) => {
  const handler = require(`${APP_ROOT}/functions/${functionName}`).handler;
  console.log(`invoking via handler function ${functionName}`); // eslint-disable-line no-console
  const context = {};
  try {
    const response = await handler(event, context);
    const contentType = _.get(
      response,
      "headers.content-type",
      "application/json"
    );
    if (response.body && contentType === "application/json") {
      response.body = JSON.parse(response.body);
    }
    return response;
  } catch (error) {
    throw error;
  }
};

node 8.10.

Was this page helpful?
0 / 5 - 0 ratings