index.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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("mail.enabled");
  29. if (this.enabled) this.transporter = nodemailer.createTransport(config.get("mail.smtp"));
  30. return new Promise(resolve => {
  31. resolve();
  32. });
  33. }
  34. /**
  35. * Sends an email
  36. *
  37. * @param {object} payload - object that contains the payload
  38. * @param {object} payload.data - information such as to, from in order to send the email
  39. * @returns {Promise} - returns promise (reject, resolve)
  40. */
  41. SEND_MAIL(payload) {
  42. return new Promise((resolve, reject) => {
  43. if (MailModule.enabled) {
  44. const { data } = payload;
  45. if (!data.from)
  46. data.from =
  47. config.get("mail.from").length > 0
  48. ? config.get("mail.from")
  49. : `${config.get("sitename")} <noreply@${config.get("url.host")}>`;
  50. MailModule.transporter
  51. .sendMail(payload.data)
  52. .then(info => {
  53. MailModule.log("SUCCESS", "MAIL_SEND", `Successfully sent email ${info.messageId}`);
  54. return resolve();
  55. })
  56. .catch(err => {
  57. MailModule.log("ERROR", "MAIL_SEND", `Failed to send email. ${err}`);
  58. return reject();
  59. });
  60. return;
  61. }
  62. resolve();
  63. });
  64. }
  65. /**
  66. * Returns an email schema
  67. *
  68. * @param {object} payload - object that contains the payload
  69. * @param {string} payload.schemaName - name of the schema to get
  70. * @returns {Promise} - returns promise (reject, resolve)
  71. */
  72. GET_SCHEMA(payload) {
  73. return new Promise(resolve => {
  74. resolve(MailModule.schemas[payload.schemaName]);
  75. });
  76. }
  77. }
  78. export default new _MailModule();