Menu

Expand
Rate this page:

Thanks for rating this page!

We are always striving to improve our documentation quality, and your feedback is valuable to us. How could this documentation serve you better?

Use Twilio Sync to create, read, update, delete peristent data

This Function showcases how you can send information into your Twilio Function from Twilio Studio's Run Function Widget and respond back with a JSON. Twilio Studio will parse the returned JSON and incorporate it into your flow.

// Description
// Use Twilio Sync to create, read, update, delete peristent data

exports.handler = function (context, event, callback) {
  // Make sure under Functions Global Config tab:
  // "Add my Twilio Credentials (ACCOUNT_SID) and (AUTH_TOKEN) to ENV" is CHECKED
  const client = context.getTwilioClient();

  // View Sync Services - https://www.twilio.com/console/sync/services
  // Set to a specific Sync Service SID
  // Set to your own sync document name to create, I use dynamicMsg

  let syncServiceSid = 'IS.....';
  let syncDocumentName = 'dynamicMsg';

  // Pass in Function to Run via URL query parameter
  // Example: https:/x.x.x.x/<path>?Function=createSyncDocument
  let functionToRun = event.Function || '';

  function createSyncDocument() {
    client.sync
      .services(syncServiceSid)
      .documents.create({
        data: {
          msg: 'Sorry we are closed.',
        },
        uniqueName: syncDocumentName,
      })
      .then((document) => {
        console.log(JSON.stringify(document.sid));
        return callback(null, 'success');
      })
      .catch((error) => {
        console.log(error);
        return callback(error);
      });
  }

  function readSyncDocument() {
    client.sync
      .services(syncServiceSid)
      .documents(syncDocumentName)
      .fetch()
      .then((document) => {
        console.log(JSON.stringify(document.data));
        return callback(null, document.data);
      })
      .catch((error) => {
        console.log(error);
        return callback(error);
      });
  }

  function updateSyncDocument() {
    client.sync
      .services(syncServiceSid)
      .documents(syncDocumentName)
      .update({
        data: {
          msg: 'We are open.',
        },
      })
      .then((document) => {
        console.log(`Documented Updated, Document SID: ${document.sid}`);
        return callback(
          null,
          `Documented Updated, Document SID: ${document.sid}`
        );
      })
      .catch((error) => {
        console.log(error);
        return callback(error);
      });
  }

  function deleteSyncDocument() {
    client.sync
      .services(syncServiceSid)
      .documents(syncDocumentName)
      .fetch()
      .then((document) => {
        client.sync.services(syncServiceSid).documents(document.sid).remove();
        return callback(null, `Document ${document.sid} Deleted`);
      })
      .catch((error) => {
        console.log(error);
        return callback(error);
      });
  }

  // Test run function via passed in parameter
  switch (functionToRun) {
    case 'createSyncDocument':
      {
        createSyncDocument();
      }
      break;
    case 'readSyncDocument':
      {
        readSyncDocument();
      }
      break;
    case 'updateSyncDocument':
      {
        updateSyncDocument();
      }
      break;
    case 'deleteSyncDocument':
      {
        deleteSyncDocument();
      }
      break;
    default:
      console.log('Please pass in the function name to execute');
      console.log('Example: https:/x.x.x.x/<path>?Function=createSyncDocument');
      return callback(
        'missing URL query parameter - Example: https:/x.x.x.x?Function=createSyncDocument'
      );
  }
};
Rate this page:

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.