Created
July 31, 2018 12:20
-
-
Save kwhinnery/37cde9ff25d76e98d79f623ea7712c31 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* global module, exports, require, process, console */ | |
'use strict' | |
const Airtable = require('airtable') | |
// Configure Airtable database | |
const base = new Airtable({ | |
apiKey: process.env.AIRTABLE_API_KEY} | |
).base(process.env.AIRTABLE_DATABASE) | |
// Get handle to Contacts tab of database | |
const contacts = base(process.env.AIRTABLE_CONTACTS_TAB) | |
// Helper to create a field update object based on selected action | |
function setFields(action) { | |
let fields = {} | |
switch (action) { | |
case 'subscribe': fields.Subscribed = true; break; | |
case 'unsubscribe': fields.Subscribed = false; break; | |
case 'rsvp_yes': fields.RSVP = true; break; | |
case 'rsvp_no': fields.RSVP = false; break; | |
} | |
return fields | |
} | |
// Create a new Contact with the given field pre-selected | |
function createContact(phoneNumber, action, callback) { | |
let fields = setFields(action) | |
fields['Phone Number'] = phoneNumber | |
contacts.create(fields, (err) => { | |
if (err) { | |
return callback(err) | |
} | |
callback(null, 'Contact created successfully!') | |
}) | |
} | |
// Query Airtable for the relevant phone number record | |
function updateContact(phoneNumber, action, callback) { | |
contacts.select({ | |
filterByFormula: `{Phone Number} = "${phoneNumber}"`, | |
}).eachPage(function page(records) { | |
let contact = records[0] | |
// Add contact to database if we don't have it | |
if (!contact) { | |
return createContact(phoneNumber, action, callback) | |
} | |
// Otherwise, update existing contact | |
let fields = setFields(action) | |
contacts.update(contact.id, fields, (err) => { | |
if (err) { | |
return callback(err) | |
} | |
callback(null, 'Contact updated successfully!') | |
}) | |
}, callback) | |
} | |
// Handle incoming SMS responses | |
exports.handler = (context, event, callback) => { | |
// Get incoming phone number and desired action from Studio flow | |
let phoneNumber = event.phone_number | |
let action = event.action | |
// Add or update contact record in Airtable | |
updateContact(phoneNumber, action, (err, message) => { | |
// Bubble an error back up to our Studio flow | |
if (err) { | |
return callback(err) | |
} | |
// Passing a null as the first argument tells Studio there was no error | |
// during execution, which will branch off into the "success" path | |
callback(null, { message }) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment