dougmoscrop / serverless-http

Use your existing middleware framework (e.g. Express, Koa) in AWS Lambda 🎉
Other
1.74k stars 167 forks source link

problem sending email using sendgrid #235

Open igorskiter opened 2 years ago

igorskiter commented 2 years ago

when trying to send email by sendgrid the lambda does not show log and ends up giving timeout. I've tried putting it inside a promise, but it didn't help. The initial handler has already been placed asyncronously. The same error also happens when I try to upload on S3. This problem only happens when it is deployed on aws, on serverless-offline it works correctly.

handler.js

import app from './';
import serverless from 'serverless-http';

const handler = serverless(app);

module.exports.handler = async (event, context) => {
  // you can do other things here
  const result = await new Promise(async (resolve, reject) => {
    const resProm = await handler(event, context);
    resolve(resProm);
  });
  // and here
  return result;
};

serveless.yml

functions:
  app:
    name: app-${env:STAGE}
    handler: src/handler.handler
    events:
      - http: ANY /
      - http: 'ANY {proxy+}'

sendMail.js

'use strict';

import crypto from 'crypto';
import sgMail from '@sendgrid/mail';

const forgetPassword = async event => {
  try{
    const { email } = event.body;

    const token = crypto.randomBytes(3).toString('hex');

    const text  = `<p>Você esqueceu sua senha?</p>
    <p>Codigo de autorização para mudar senha: ${token}</p>
    <p>Se não pediu para recuperar a senha ignore esse e-amil.</p>`;

    const msg = {
      to: [<<EMAIL>>],
      from: 'noreplay@playspts.com.br',
      subject: 'Código para resetar senha',
      text,
      html: text
    }

    sgMail.setApiKey(process.env.SENDGRID_API_KEY);

    const sendMail = await sgMail.send(msg);

    console.log( sendMail);

    return {
      statusCode: 200,
      body: JSON.stringify(
        {
          message: 'Pedido de token enviado, verifique seu e-mail!',
          sendMail
        }
      ),
    }
  }catch(e){
      console.error(e, "forgetPassword EROOR");
  }
  return {
    statusCode: 400,
    error: true,
    body: JSON.stringify(
      {
        message: 'Falha na recuperação da senha!',
        input: event,
      }
    ),
  }
}

export default Auth;
dougmoscrop commented 2 years ago
const result = await new Promise(async (resolve, reject) => {
    const resProm = await handler(event, context);
    resolve(resProm);
  });

This is risky, the Promise constructor does not, as far as I know, respect rejected promises and will therefore never settle. It's posisble you have an unhandled rejection being swallowed; you should at least do:

try { res = await .. resolve(res) } catch (e) { reject(e) }

but of course, you can see that this entire promise wrapper is not useful as you can just move the await up!