In Feathers.js hooks are the go-to place for adding logic to your services. They consist of 3 main categories: before, after and error. They are defined for all possible CRUD events: find, get, create, update, patch, remove and all.
Before Hooks
We will first have a look at the hooks we attach before we do something with the service. Before you create an email, you want to ensure the default values are set correctly. We handle this by using the setDefaultValues() function.
Let’s break it down. Firstly, you want to ensure that the created request contains data; otherwise, it is not valid.
Then the switch double-checks whether this is used for the create method, by checking whether `context.method === ‘create’`. Then you will want to extract your SMTP config object. We store it in the app’s context, which we suggest you should do as well. However, let’s suppose that you are using some other method of storing the information. In that case, you will need to extract the from.name and from.address.
Then, unless your user provides an explicit value for the text field, you will need to parse the provided html to plain-text. For this, we use the html-to-text
package.
Next, you check whether the request provides you with the from data. In the case that it doesn’t, you want to use the data about the account you specified in the SMTP config.
The user might not provide you with a name for the email; in that case, you want to generate the name automatically. Then we construct it from the recipient and the subject of the email.
Finally, you need to ensure that the email is created with the pending status. Regardless of what the user sends you, always set the status to pending. There is no reason to construct emails which are by default completed or failed.
After Hooks
Having all of the data prepared on the before hooks, we can now move on to the after hooks. Here only one hook will be in use – the create hook. The logic is that you will send the email after the email object was created in your database. The sendEmail function manages this.
Let’s break this function down a bit. First, we define all of our variables.
Having these variables, we can attempt to send the email. The attempt aspect is essential; there are multiple ways in which an email can fail to send, so you must ensure that you capture any possible errors.
Finally, all you are left with is to save the result to your database. You may also want to throw the error at the end if you also have some other method of managing errors in Feathers.