sendgrid google cloud functions nodejs code example

Example: inbound email sendgrid cloud functions

import * as functions from 'firebase-functions';
import * as express from 'express';
const formidable = require('formidable-serverless');

export class InboundEmail {
  constructor(from, subject, text, html, to) {}
  doStrategy() {
     //Store inbound email
     //Send outbound email
     //...
  }
}

export class EmailPostWebHook {
  private form = new formidable.IncomingForm();
  private incomeEmail: IncomeEmail;

  async run(request: express.Request, res: express.Response) {
    try {
      this.parse(request);
      await this.incomeEmail.doStrategy();
    } catch (e) {
      console.log(e);
    }
    return res.sendStatus(200);
  }

  private parse(request: express.Request) {
    this.form.parse(request, (errors: any, fields: any) => {
      this.incomeEmail = new IncomeEmail(
        fields.from
        fields.subject,
        fiels.text
        fields.html,
        fields.to
      );
    });
  }
}


const app = express();

const emailPostWebHook = new EmailPostWebHook();
app.post('/', emailPostWebHook.run.bind(emailPostWebHook));

export const InboundEmailHook = functions
  .runWith({
    timeoutSeconds: 30,
    memory: '2GB',
  })
  .https.onRequest(app);