Skip to content
Advertisement

Twilio Studio and Rebrandly link shortener – Return parsed rather than string

I adapted some instructions in order to Twilio Studio to obtain a shortened URL via a function which talks to the Rebrandly API. It works fine except the data returned is in a string rather than parsed, as can be seen here:

Studio Log

The code provided by Rebrandly is:

exports.handler = function(context, event, callback) {
  let response = { get_started: true };

let request = require("request");
let linkRequest = {
  destination: "https://www.carecalls.co.uk/conferma-ricevuta?num=" + event.receiver,
  domain: { fullName: "link.carecalls.co.uk" }
  //, slashtag: "A_NEW_SLASHTAG"
  //, title: ""
}

let requestHeaders = {
  "Content-Type": "application/json",
  "apikey": "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "workspace": "XXXXXXXXXXXXXXXXXXXXXXXXXXXX"
}

request({
    uri: "https://api.rebrandly.com/v1/links",
    method: "POST",
    body: JSON.stringify(linkRequest),
    headers: requestHeaders
}, (err, response, body) => {
  let link = JSON.parse(body);
  console.log(`Long URL was ${link.destination}, short URL is ${link.shortUrl}`);
  callback(null, response);
});
};

What do I need to change in order to get a parsed list that studio can use to populate variables? I’m a pretty green developer so hoping this is obvious to someone! Help much appreciated

Advertisement

Answer

Twilio developer evangelist here.

In the function you supplied, you are returning the entire response object back to Twilio. The object is JSON stringified, but since the body of the response was already JSON, it has been double escaped. Studio will parse the response, but this will only parse the body once instead of the twice it would need.

Instead of returning the entire response, I would suggest just returning the body of the response. You already parsed the body to a variable link, so just return that variable to the callback function instead:

  }, (err, response, body) => {
    let link = JSON.parse(body);
    console.log(`Long URL was ${link.destination}, short URL is ${link.shortUrl}`);
    callback(null, link); // << return link here
  });
};

Doing this will give you that parsed response body that you want to be using.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement