One of the more abstract concepts you'll handle when building your business is what the workflow will look like.
At its core, setting up a standardized workflow is about enabling your service providers (agents, hosts, customer service reps, administrators, and the rest of the gang) to better serve your customers.
To illustrate a very real-world example, today we'll build a Node.js and Express webapp for finding and booking vacation properties — tentatively called Airtng.
Here's how it'll work:
We'll be using the Twilio REST API to send our users messages at important junctures. Here's a bit more on our API:
Ready to go? Boldly click the button right after this sentence.
For this workflow to work, we need to handle user authentication. We're going to rely on Passport for Node.js.
Each User
will need to have a countryCode
and a phoneNumber
which will be required to send SMS notifications later.
models/user.js
1var mongoose = require('mongoose');2var passportLocalMongoose = require('passport-local-mongoose');34var userSchema = new mongoose.Schema({5email: { type: String, required: true },6username: { type: String, required: true },7password: { type: String },8countryCode: { type: String, required: true },9phoneNumber: { type: String, required: true },10date: { type: Date, default: Date.now },11});1213userSchema.plugin(passportLocalMongoose);1415var user = mongoose.model('user', userSchema);1617module.exports = user;
Next let's model the vacation properties.
In order to build our rentals company we'll need a way to create the property listings.
The Property
belongs to the User
who created it (we'll call this user the host moving forward) and contains only two properties: a description
and an imageUrl
.
models/property.js
1var mongoose = require('mongoose');23var propertySchema = new mongoose.Schema({4description: { type: String, required: true },5imageUrl: { type: String, required: true },6date: { type: Date, default: Date.now },7owner: {8type: mongoose.Schema.Types.ObjectId,9ref: 'user'10}11});1213var property = mongoose.model('property', propertySchema);1415module.exports = property;
Next up, the reservation model.
The Reservation
model is at the center of the workflow for this application.
It is responsible for keeping track of:
guest
who performed the reservationvacation_property
the guest is requesting (and associated host)status
of the reservation: pending
, confirmed
, or rejected
models/reservation.js
1var mongoose = require('mongoose');2var deepPopulate = require('mongoose-deep-populate')(mongoose);34var reservationSchema = new mongoose.Schema({5message: { type: String, required: true },6status: { type: String, default: 'pending' },7date: { type: Date, default: Date.now },8property: {9type: mongoose.Schema.Types.ObjectId,10ref: 'property'11},12guest: {13type: mongoose.Schema.Types.ObjectId,14ref: 'user'15}16});1718reservationSchema.plugin(deepPopulate, {});1920var reservation = mongoose.model('reservation', reservationSchema);2122module.exports = reservation;
Next, let's look at triggering the creation of a new reservation.
The reservation creation form holds only a single field field: the message that will be sent to the host when reserving one of her properties. The rest of the information necessary to create a reservation is taken from the vacation property.
A reservation is created with a default status pending
, so when the host replies with an accept
or reject
response our application knows which reservation to update.
routes/reservations.js
1var MessagingResponse = require('twilio').twiml.MessagingResponse;2var twilio = require('twilio');3var express = require('express');4var router = express.Router();5var Property = require('../models/property');6var Reservation = require('../models/reservation');7var User = require('../models/user');8var notifier = require('../lib/notifier');910// POST: /reservations11router.post('/', function (req, res) {12var propertyId = req.body.propertyId;13var user = req.user;1415Property.findOne({ _id: propertyId })16.then(function (property) {17var reservation = new Reservation({18message: req.body.message,19property: propertyId,20guest: user.id21});2223return reservation.save();24})25.then(function () {26notifier.sendNotification();27res.redirect('/properties');28})29.catch(function(err) {30console.log(err);31});32});3334// POST: /reservations/handle35router.post('/handle', twilio.webhook({validate: false}), function (req, res) {36var from = req.body.From;37var smsRequest = req.body.Body;3839var smsResponse;4041User.findOne({phoneNumber: from})42.then(function (host) {43return Reservation.findOne({status: 'pending'});44})45.then(function (reservation) {46if (reservation === null) {47throw 'No pending reservations';48}49reservation.status = smsRequest.toLowerCase() === "accept" ? "confirmed" : "rejected";50return reservation.save();51})52.then(function (reservation) {53var message = "You have successfully " + reservation.status + " the reservation";54respond(res, message);55})56.catch(function (err) {57var message = "Sorry, it looks like you do not have any reservations to respond to";58respond(res, message);59});60});6162var respond = function(res, message) {63var messagingResponse = new MessagingResponse();64messagingResponse.message({}, message);6566res.type('text/xml');67res.send(messagingResponse.toString());68}6970module.exports = router;
In the next step, we'll take a look at how the SMS notification is sent to the host when the reservation is created.
When a reservation is created, we want to notify the owner of said property that someone has made a reservation.
This is where we use Twilio Node Helper Library to send an SMS message to the host, using our Twilio phone number. As you can see, sending SMS messages using Twilio is just a few lines of code.
Now we just have to wait for the host to send an SMS response accepting or rejecting the reservation so we can notify the guest and host that the reservation information is updated.
Notify through SMS the host of the new reservation
1var config = require('../config');2var client = require('twilio')(config.accountSid, config.authToken);3var Reservation = require('../models/reservation');45var sendNotification = function() {6Reservation.find({status: 'pending'})7.deepPopulate('property property.owner guest')8.then(function (reservations) {9if (reservations.length > 1) {10return;11}1213var reservation = reservations[0];14var owner = reservation.property.owner;1516// Send the notification17client.messages.create({18to: phoneNumber(owner),19from: config.phoneNumber,20body: buildMessage(reservation)21})22.then(function(res) {23console.log(res.body);24})25.catch(function(err) {26console.log(err);27});28});29};3031var phoneNumber = function(owner) {32return "+" + owner.countryCode + owner.phoneNumber;33};3435var buildMessage = function(reservation) {36var message = "You have a new reservation request from " + reservation.guest.username +37" for " + reservation.property.description + ":\n" +38reservation.message + "\n" +39"Reply accept or reject";4041return message;42};4344exports.sendNotification = sendNotification;
The next step shows how to handle and configure the host's SMS response.
The reservations/handle
endpoint handles our incoming Twilio request and does three things:
In the Twilio console, you should change the 'A Message Comes In' webhook to call your application's endpoint in the route /handle:
One way to expose your machine to the world during development is to use ngrok. Your URL for the SMS web hook on your phone number should look something like this:
http://<subdomain>.ngrok.io/handle
An incoming request from Twilio comes with some helpful including the From
phone number and the message Body
.
We'll use the From
parameter to lookup the host and check if she has any pending reservations. If she does, we'll use the message body to check if she accepted or rejected the reservation.
routes/reservations.js
1var MessagingResponse = require('twilio').twiml.MessagingResponse;2var twilio = require('twilio');3var express = require('express');4var router = express.Router();5var Property = require('../models/property');6var Reservation = require('../models/reservation');7var User = require('../models/user');8var notifier = require('../lib/notifier');910// POST: /reservations11router.post('/', function (req, res) {12var propertyId = req.body.propertyId;13var user = req.user;1415Property.findOne({ _id: propertyId })16.then(function (property) {17var reservation = new Reservation({18message: req.body.message,19property: propertyId,20guest: user.id21});2223return reservation.save();24})25.then(function () {26notifier.sendNotification();27res.redirect('/properties');28})29.catch(function(err) {30console.log(err);31});32});3334// POST: /reservations/handle35router.post('/handle', twilio.webhook({validate: false}), function (req, res) {36var from = req.body.From;37var smsRequest = req.body.Body;3839var smsResponse;4041User.findOne({phoneNumber: from})42.then(function (host) {43return Reservation.findOne({status: 'pending'});44})45.then(function (reservation) {46if (reservation === null) {47throw 'No pending reservations';48}49reservation.status = smsRequest.toLowerCase() === "accept" ? "confirmed" : "rejected";50return reservation.save();51})52.then(function (reservation) {53var message = "You have successfully " + reservation.status + " the reservation";54respond(res, message);55})56.catch(function (err) {57var message = "Sorry, it looks like you do not have any reservations to respond to";58respond(res, message);59});60});6162var respond = function(res, message) {63var messagingResponse = new MessagingResponse();64messagingResponse.message({}, message);6566res.type('text/xml');67res.send(messagingResponse.toString());68}6970module.exports = router;
In the last step, we'll use Twilio's TwiML and instruct Twilio to send SMS messages to the guest.
After updating the reservation status, we must notify the host that they have successfully confirmed or rejected the reservation. If no reservation is found, we send an error message instead.
If a reservation is confirmed or rejected we send an additional SMS to the guest to pass along the news.
We use the verb Message from TwiML to instruct Twilio's server that it should send SMS messages.
routes/reservations.js
1var MessagingResponse = require('twilio').twiml.MessagingResponse;2var twilio = require('twilio');3var express = require('express');4var router = express.Router();5var Property = require('../models/property');6var Reservation = require('../models/reservation');7var User = require('../models/user');8var notifier = require('../lib/notifier');910// POST: /reservations11router.post('/', function (req, res) {12var propertyId = req.body.propertyId;13var user = req.user;1415Property.findOne({ _id: propertyId })16.then(function (property) {17var reservation = new Reservation({18message: req.body.message,19property: propertyId,20guest: user.id21});2223return reservation.save();24})25.then(function () {26notifier.sendNotification();27res.redirect('/properties');28})29.catch(function(err) {30console.log(err);31});32});3334// POST: /reservations/handle35router.post('/handle', twilio.webhook({validate: false}), function (req, res) {36var from = req.body.From;37var smsRequest = req.body.Body;3839var smsResponse;4041User.findOne({phoneNumber: from})42.then(function (host) {43return Reservation.findOne({status: 'pending'});44})45.then(function (reservation) {46if (reservation === null) {47throw 'No pending reservations';48}49reservation.status = smsRequest.toLowerCase() === "accept" ? "confirmed" : "rejected";50return reservation.save();51})52.then(function (reservation) {53var message = "You have successfully " + reservation.status + " the reservation";54respond(res, message);55})56.catch(function (err) {57var message = "Sorry, it looks like you do not have any reservations to respond to";58respond(res, message);59});60});6162var respond = function(res, message) {63var messagingResponse = new MessagingResponse();64messagingResponse.message({}, message);6566res.type('text/xml');67res.send(messagingResponse.toString());68}6970module.exports = router;
And that's a wrap! Next let's take a look at other features you might enjoy in your application.
Node.js goes great with a helping of Twilio... let us prove it:
You can route callers to the right people and information with an IVR (interactive voice response) system.
Instantly collect structured data from your users with a survey conducted over a voice call or SMS text messages.