index.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /* eslint-disable global-require */
  2. import config from "config";
  3. import nodemailer from "nodemailer";
  4. import CoreClass from "../../core";
  5. let MailModule;
  6. class _MailModule extends CoreClass {
  7. // eslint-disable-next-line require-jsdoc
  8. constructor() {
  9. super("mail");
  10. MailModule = this;
  11. }
  12. /**
  13. * Initialises the mail module
  14. *
  15. * @returns {Promise} - returns promise (reject, resolve)
  16. */
  17. async initialize() {
  18. const importSchema = schemaName =>
  19. new Promise(resolve => {
  20. import(`./schemas/${schemaName}`).then(schema => resolve(schema.default));
  21. });
  22. this.schemas = {
  23. verifyEmail: await importSchema("verifyEmail"),
  24. resetPasswordRequest: await importSchema("resetPasswordRequest"),
  25. passwordRequest: await importSchema("passwordRequest"),
  26. dataRequest: await importSchema("dataRequest")
  27. };
  28. this.enabled = config.get("smtp.enabled");
  29. if (this.enabled)
  30. this.transporter = nodemailer.createTransport({
  31. host: config.get("smtp.host"),
  32. port: config.get("smtp.port"),
  33. secure: config.get("smtp.secure"),
  34. auth: {
  35. user: config.get("smtp.auth.user"),
  36. pass: config.get("smtp.auth.pass")
  37. }
  38. });
  39. return new Promise(resolve => resolve());
  40. }
  41. /**
  42. * Sends an email
  43. *
  44. * @param {object} payload - object that contains the payload
  45. * @param {object} payload.data - information such as to, from in order to send the email
  46. * @returns {Promise} - returns promise (reject, resolve)
  47. */
  48. SEND_MAIL(payload) {
  49. return new Promise((resolve, reject) => {
  50. if (MailModule.enabled)
  51. return MailModule.transporter
  52. .sendMail(payload.data)
  53. .then(info => {
  54. MailModule.log("SUCCESS", "MAIL_SEND", `Successfully sent email ${info.messageId}`);
  55. return resolve();
  56. })
  57. .catch(err => {
  58. MailModule.log("ERROR", "MAIL_SEND", `Failed to send email. ${err}`);
  59. return reject();
  60. });
  61. return resolve();
  62. });
  63. }
  64. /**
  65. * Returns an email schema
  66. *
  67. * @param {object} payload - object that contains the payload
  68. * @param {string} payload.schemaName - name of the schema to get
  69. * @returns {Promise} - returns promise (reject, resolve)
  70. */
  71. GET_SCHEMA(payload) {
  72. return new Promise(resolve => {
  73. resolve(MailModule.schemas[payload.schemaName]);
  74. });
  75. }
  76. }
  77. export default new _MailModule();