How to add mail notification to Sequelize
Tags: node, sequelize, nodemailer, notification
Published: 2020-05-26 14:45:03

Laravel's Eloquent (ORM) offers a notification trait that enables you send notification from the model itself. As sequelize doesn't ship with a notify method as Eloquent, we would be creating our own. 

Sounds exciting right? Lets dig in!!! 

Note: Basic knowledge of Sequelize and Nodemailer is needed. Try reading up on them first :). 

We would be kicking things off by creating our package directory called "sequelizeNotifier".

So, lets get this party started!!!

<h3>Create sequelizeNotifier entry point.</h3>
 We kick things off by creating an entry point for our package. To do this, we would create an index.js file in the root path of our package. We then pass the Sequelize object then extend it by adding a notify function to its prototype. We also pass a config parameter for our transport configuration. Don't bother about the dependicies, we are going to create them let's just keep going.

**sequelizeNotifier/index.js**
```js
 const notifier = require('./src/notify');
 const transport = require('./src/mailer');

 module.exports = function (Sequelize,config) {
    
    Sequelize.Model.prototype.notify = function (options){
       let initTransport = transport(config);
       return  notifier(this,initTransport,options);
    }

};
```

 <h3>Create the Mail Object.</h3>
 Now let us create a mail function that initializes the nodemailer transport in which returns this transport back to us.

  **sequelizeNotifier/src/mailer.js**
 ```js
 const nodemailer = require('nodemailer');

 module.exports = function mailer(config) {
    
        try{

            let transport =  nodemailer.createTransport(config);
            return transport;

        }catch (e) {
            console.warn(e);
        }
   
}
```
 
<h3> Create the notifier</h3>

 **sequelizeNotifier/src/notify.js**
Finally, let us create the "notify" method. This is the method that would be called anytime we call the notify method from the sequelize model. 

```js
 module.exports = function  notify (model,transport,options) {

    try{
        let mail =  transport.sendMail({
            from:'no-reply@myapp.com',
            to:model.email,
            ...options
        });
        console.log(mail)
    }catch (e) {
        console.log(e)
    }
}


```

 
Pheewwww we are almost done. It's time to test this beast!!!

<h3>Usage: </h3>
I am sure you might have a different approach for configuring your application with Sequelize, but in-respective of your configuration style, just pass  the **sequelize** package into our **sequelizeNotifier** package with it's configuation and we are good to go

```js
const Sequelize = require('sequelize');
const config = {
                host:'smtp.example.com',
                port:"273",
                secure:"false",
                auth:{
                    user:"james",
                    pass:"example"
                }
            }
require('path/to/sequelizeNotifier')(Sequelize,config);
//more codes 
```
Now let's assume we have our **register.js** file for registering a new user. After creating the user, you would want to notify the user her account has been created. Here is a snippet of **register.js**:

```js
 const {User} = require('./models');
 module.exports = function register(req,res){
   try{
     const user = await User.create({
       name:"chiemeke Ifeanyi",
       email:"example@gmail.com"
     });
     //send mail
     const messageObject = {
                        subject: "Account Created Successfully",
                        text: `Hi ${user.name}, welcome to my app`,
                    }
     user.notify(messageObject);
   }catch(e){
    //catch eror
   }
   
}
 
//more codes
```
For more options to use with the messageObject, check out the [nodemailer documentation here](https://nodemailer.com/message/) for sending messages.

That would be all folks.