Difficulty: Beginner
Estimated Time: 10 minutes

let URL = require('url'); let request = require('request'); let Airtable = require('airtable'); require("pinkie-promise-cdn");

Airtable.configure({ endpointUrl: 'https://api.airtable.com', apiKey: process.env.AIRTABLE_API_KEY });

let reservedkeys = [ 'base_id', 'user_created_block', 'user_updated_block',

];

let sendResponse = (response, data) => { response.writeHead(200, { 'Content-Type': 'application/json' }); response.end( JSON.stringify(data) ); }

let dataTableHandler = (res, query, type) => (err, user) => { if (err) { sendResponse(res, err); return; }

if (type === 'create' && query.user_created_block) {
      sendResponse(res, { redirect_to_blocks: [query.user_created_block] });
  } else if (type === 'update' && query.user_updated_block) {
      sendResponse(res, { redirect_to_blocks: [query.user_updated_block] });
  } else {
      sendResponse(res, {});
  }
  

}

let getOnlyUserData = (data) => { return Object.keys(data).reduce(function(newObj, key) { if (!reservedkeys.includes(key.toLowerCase())) { newObj[key] = data[key]; } return newObj; }, {}); }

let handleMissingParameter = (res, parameterName) => { let text = "${parameterName}" query parameter missing on JSON URL endpoint; let textMsg = { text }; sendResponse(res, [textMsg]); }

exports.endpoint = function(req, res) { let query = URL.parse(req.url, true).query;

// Check for missing parameters
  if (!query.base_id) {
      handleMissingParameter(res, 'base_id');
      return;
  }
  

if (!query['messenger user id']) { handleMissingParameter(res, 'messenger user id'); return; }

// Get Base
  

let base = Airtable.base(query.base_id); let dataTable = base('Data');

// Find User
  

dataTable.select({ maxRecords: 1, fields: ['messenger user id'], filterByFormula: {messenger user id} = '${query['messenger user id']}' })

.firstPage(function(error, records) { // Send Airtable Errors if any if (error) { sendResponse(res, { error, error_source: 'airtable' }); return; }

let user = records[0]; let data = getOnlyUserData(query); if (user) { // Update Existing User Data dataTable.update( user.id, data, dataTableHandler(res, query, 'update') ); } else { // Create New User When User Doesn't Exist dataTable.create( data, dataTableHandler(res, query, 'create') ); } }); }

Don’t stop now! The next scenario will only take about 10 minutes to complete.

Datafeed

App