Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

81 строка
2.4 KiB

  1. import express from 'express'
  2. import cors from 'cors'
  3. import bodyParser from 'body-parser'
  4. import amqp from 'amqplib'
  5. import dotenv from 'dotenv'
  6. import sgMail from '@sendgrid/mail'
  7. dotenv.config()
  8. const app = express()
  9. const queuePaylater = process.env.QUEUE_PAYLATER
  10. const queueNota = process.env.QUEUE_NOTA
  11. const senderEmail = process.env.SENDER_EMAIL
  12. const apiKey = process.env.SENDGRIP_API_KEY
  13. sgMail.setApiKey(apiKey)
  14. app.use(cors())
  15. app.use(bodyParser.json())
  16. app.get('/', (_req, res) => {
  17. res.status.send(200).send("Amigo Receipt Sender Service Homepage!")
  18. })
  19. amqp.connect(process.env.AMQP_SERVER).then(async conn => {
  20. const ch = await conn.createChannel()
  21. const queuePaylaterExist = ch.assertQueue(queuePaylater, { durable: true });
  22. const queueNotaExist = ch.assertQueue(queueNota, { durable: true })
  23. if (queueNotaExist) {
  24. queueNotaExist.then(() => {
  25. return ch.consume(queueNota, async (msg) => {
  26. var messageBody = JSON.parse(msg.content.toString())
  27. console.log(`[*NOTA] Message Received! email : ${messageBody.email}`)
  28. sendReceipt({
  29. email: messageBody.email,
  30. subject: messageBody.subject,
  31. content: messageBody.content,
  32. })
  33. }, { noAck: true })
  34. }).then(() => {
  35. console.log('* Waiting for messages from queue ' + queueNota)
  36. })
  37. }
  38. if (queuePaylaterExist) {
  39. queuePaylaterExist.then(() => {
  40. return ch.consume(queuePaylater, async (msg) => {
  41. var messageBody = JSON.parse(msg.content.toString())
  42. console.log(`[*PayLater] Message Received! email : ${messageBody.email}`)
  43. sendReceipt({
  44. email: messageBody.email,
  45. subject: messageBody.subject,
  46. content: messageBody.content,
  47. })
  48. }, { noAck: true })
  49. }).then(() => {
  50. console.log('* Waiting for messages from queue ' + queuePaylater)
  51. })
  52. }
  53. }).catch(console.warn)
  54. function sendReceipt(message) {
  55. const now = new Date()
  56. const msg = {
  57. to: message.email,
  58. from: senderEmail,
  59. subject: message.subject,
  60. html: message.content,
  61. }
  62. sgMail
  63. .send(msg)
  64. .then((response) => {
  65. if (response[0].statusCode == 202) {
  66. console.log(`Email sent to ${message.email} at ${now}`)
  67. } else {
  68. console.error(`Failed to send email to ${message.email} at ${now}`)
  69. }
  70. })
  71. .catch((error) => {
  72. console.error(error)
  73. })
  74. }