Twilio: Temporary Storage in a Twilio Function

Viewed 89

I'm not really understand what's the temporary storage means.

recently I have an issue:

We can deliver a variable to the function by TwiML, but it's have size/length limit. So I have to save this variable to global, so I can get this variable in anywhere(function) I want. But I'm worry if the variable will be changed by some others, because our function in twilio is serverless. In fact, global variable is not safe. Anyone can solve this?

I want to ask may I use temporary storage to resolve this?

Thanks.

2 Answers

Twilio developer evangelist here.

A coworker, a solutions engineer based in the UK, wrote this great blog post on using temporary storage in a Twilio Function.

The code in your Twilio Function would look something like

/**
*
*  This Function shows you how to reach and utilise the temporary storage under the Function layer, mainly for single-invocation jobs
*  For example, on each invocation we can create a file based on user data and use it accordingly
*
*  IMPORTANT: Do NOT treat this storage as long term storage or for personal data that need to persist.
*  The contents get deleted whenever the associated container is brought down, so this function is useful for one time actions
*
*/
var fs = require('fs');
var path = require('path');
var tmp_dir = require('os').tmpdir();

exports.handler = function(context, event, callback) {

   /*We create a text file and we put some data in it*/
   fs.writeFile(path.join(tmp_dir, 'test_file.txt'), 'Contents of created file in OS temp directory', function(err) {
       if (err) callback(err);

       /*We read the contents of the temporary directory to check that the file was created. For multiple files you can create a loop*/
       fs.readdir(tmp_dir, function(err, files) {
           if (err) callback(err);

           callback(null, "File created in temporary directory: " + files.join(", "));
       });
   });
};

If you want to use temporary storage from the Twilio CLI, you can do so by running this command inside a project that you created with the Serverless Toolkit:

twilio serverless:new example --template=temp-storage

This Function template is also here on the Twilio Labs GitHub page.

Let me know if this helps at all!

enter image description here

The code looks like this:

  1. In widget api_get_account_status, I save correlationId to function storage-CallSid;
  2. In function storage-CallSid, I save correlationId to the "temporary storage";
  3. In widget split_check_call_type, I invoke another function get-storage-CallSid;
  4. In function get-storage-CallSid, may I get correlationId from "temporary storage"?
Related