0

I have a problem with my NestJS application.

Under specific endpoint ('/email') I have a service call, that make a call to mongoDB at first with getData() method. Then with the returned data, it calls mailService to send an email. The mailService creates PDF, then converts it to base64 and sends it in attachment with nodemailer.

The promise from this.mailerService.sendMail() is ignored somehow. Request under localhost:3000/email returns status 200 with empty response and the email has been sent. How can I return data from this.mailerService.sendMail() call with this endpoint?

controller.ts

  @UseGuards(JwtAuthGuard)
  @Get('email')
  async sendEmail() {
    const emails = {
      receivers: ['jon@doe.com'],
      cc: ['jon@doe.com'],
    };
    return await this.dataService
      .getData()
      .then((data) => this.mailService.sendUserConfirmation(emails, data));
  }

dataService.ts

async getData(): Promise<EmailData> {
    return this.emailDataModel.findOne({ _id: 1});
  }

mailService.ts

  async sendUserConfirmation(emails: EmailList, data: emailData) {
    return await pdfMake
      .createPdf(this.prepareDoc(data))
      .getBase64((encodedString) => {
        const emailOptions = this.prepareEmail(
          emails,
          encodedString,
          data.docName,
        );
        return this.mailerService.sendMail(emailOptions);
      });
  }
mhld
  • 163
  • 2
  • 9
  • are you sure that `getBase64` returns a promise? If so, this promise resolves to the value returned by `getBase64` callback? – Micael Levi Oct 01 '21 at 20:12
  • @MicaelLevi as mentioned here in [47154507](https://stackoverflow.com/questions/47154507/pdfmake-function-getbase64-return-undefined-value) this function returns promise. – mhld Oct 01 '21 at 20:25
  • 1
    actually it doesn't returns a promise (read [this](https://stackoverflow.com/a/47156177/5290447)). This is why you need to create a new promise to use it :p – Micael Levi Oct 01 '21 at 23:31

1 Answers1

1

Fixed, had to fix mailService.ts

  async sendUserConfirmation(
    emails,
    data
  ): Promise<string> {
    return new Promise((resolve) => {
      pdfMake.createPdf(this.prepareDoc(data)).getBase64((data) => {
        const emailOptions = this.prepareEmail(emails, data, data.docName);
        return resolve(this.mailerService.sendMail(emailOptions));
      });
    });
  }
mhld
  • 163
  • 2
  • 9