index.js 2.3 KB

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