index.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. };
  27. this.enabled = config.get("smtp.enabled");
  28. if (this.enabled)
  29. this.transporter = nodemailer.createTransport({
  30. host: config.get("smtp.host"),
  31. port: config.get("smtp.port"),
  32. secure: config.get("smtp.secure"),
  33. auth: {
  34. user: config.get("smtp.auth.user"),
  35. pass: config.get("smtp.auth.pass")
  36. }
  37. });
  38. return new Promise(resolve => resolve());
  39. }
  40. /**
  41. * Sends an email
  42. *
  43. * @param {object} payload - object that contains the payload
  44. * @param {object} payload.data - information such as to, from in order to send the email
  45. * @returns {Promise} - returns promise (reject, resolve)
  46. */
  47. SEND_MAIL(payload) {
  48. return new Promise((resolve, reject) => {
  49. if (MailModule.enabled)
  50. return 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 resolve();
  61. });
  62. }
  63. /**
  64. * Returns an email schema
  65. *
  66. * @param {object} payload - object that contains the payload
  67. * @param {string} payload.schemaName - name of the schema to get
  68. * @returns {Promise} - returns promise (reject, resolve)
  69. */
  70. GET_SCHEMA(payload) {
  71. return new Promise(resolve => {
  72. resolve(MailModule.schemas[payload.schemaName]);
  73. });
  74. }
  75. }
  76. export default new _MailModule();