Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
/* 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}
// 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) {{
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(, 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