In this lab you will add publish subscribe to the contacts service from the last lab. We will implement the confirmation email example from the Microservices talk.
Create an account with PubNub
Create an account with MailGun .
Update the contact service to publish to your PubNub publish subscribe service. Add the PubNub.js package to your service using NPM
npm install pubnub --save
In the base folder of the contacts service, add a new folder called config. In the config folder, create a new module called pubsub.js and add the following code. Use your keys from the PubNub:
'use strict';
// Mail service configuration
// ===========================
module.exports = require("pubnub").init({
publish_key : "pub-c-xxx",
subscribe_key : "sub-c-xxx"
});
In api/contacts/app.js initialise the api by adding the following code just under the mongodb initialisation.
var pubnub = require("../../config/pubnub.js")
Now add the following code to the callback function on creation of a contact:
pubnub.publish({
channel: 'create_contact_event',
message: JSON.stringify(contact),
callback : function(m){console.log('New_Contact_Event:' + m)}
});
Test your service by adding a new contact. Check the console to see if the event is successfully published.
Add the MailGun-js Package to your service
npm install mailgun-js --save
Create a new Node application that subscribes to your PubNub app and sends a confirmation mail every time a new contact event is created In the base folder of your service, create a new file called mail_app.js and add the following code, updating the key and domain values from your MailGun account:
var api_key = 'key-xxx';
var domain = 'sandboxxxx.mailgun.org';
var mailgun = require('mailgun-js')({apiKey: api_key, domain: domain});
var pubnub = require('./config/pubnub.js');
// Subscribe to the demo_tutorial channel
pubnub.subscribe({
channel: 'create_contact_event',
message: function(m){console.log('Send email to '+JSON.parse(m).email);
var data = {
from: 'WIT BSc IT <me@wit.ie>',
to: JSON.parse(m).email,
subject: 'Welcome',
text: 'Welcome to the company!!!'
};
mailgun.messages().send(data, function (error, body) {
console.log(body);
});
}
});
Now test by adding a contact via your api. Make sure to include an email field in the contact object.