Search code examples
apigoogle-apps-scriptlooker-studio

Data Studio - community connector - how to add user token?


I want to connect to a REST API. This works great with google sheets and scripts. But now i don't know how i can insert the token required. It needs to be in the header of the GetRequest so i tryed this code. But when i launch trough manifest file i get an error:

There was an error caused by this connector.

My script

As you can see i try to pass the token within the getData(). Somy knows the solution?

/**
 * Original: Ben Collins
 * 2018
 * Changed by: Remco Edelenbos
 * 2020
 */


/**
* Returns Data Studio configuration settings
*
* @param {object} javaScript object containing the config request parameters
*
* @returns {array} javaScript object representing the connector configuration that should be displayed to the user.
*/
function getConfig(request) {

  var config = {
    configParams: []
  };

  return config;

};


var connectorJson = [
    {
      "id": "Jaartal",
      "fieldId": "U012",
      "dataType": "int",
      "label": "Jaartal",
      "length": 4,
      "controlType": 1,
      "decimals": 0,
      "decimalsFieldId": ""
    },
    {
      "id": "Project_code",
      "fieldId": "U001",
      "dataType": "string",
      "label": "Projectnummer",
      "length": 15,
      "controlType": 5,
      "decimals": 0,
      "decimalsFieldId": ""
    },
    {
      "id": "Title",
      "fieldId": "U003",
      "dataType": "string",
      "label": "Projectomschrijving",
      "length": 100,
      "controlType": 1,
      "decimals": 0,
      "decimalsFieldId": ""
    },
    {
      "id": "Hoofdproject",
      "fieldId": "U013",
      "dataType": "string",
      "label": "Hoofdproject",
      "length": 100,
      "controlType": 1,
      "decimals": 0,
      "decimalsFieldId": ""
    },
    {
      "id": "Verkooprelatie",
      "fieldId": "U008",
      "dataType": "string",
      "label": "Verkooprelatie",
      "length": 255,
      "controlType": 1,
      "decimals": 0,
      "decimalsFieldId": ""
    },
    {
      "id": "Project_groep",
      "fieldId": "U002",
      "dataType": "string",
      "label": "Projectgroep",
      "length": 15,
      "controlType": 5,
      "decimals": 0,
      "decimalsFieldId": ""
    },
    {
      "id": "Start",
      "fieldId": "U010",
      "dataType": "string",
      "label": "Start event (tijd)",
      "length": 50,
      "controlType": 1,
      "decimals": 0,
      "decimalsFieldId": ""
    },
    {
      "id": "End",
      "fieldId": "U011",
      "dataType": "string",
      "label": "Eind event (tijd)",
      "length": 50,
      "controlType": 1,
      "decimals": 0,
      "decimalsFieldId": ""
    },
    {
      "id": "Code",
      "fieldId": "U014",
      "dataType": "string",
      "label": "Code",
      "length": 15,
      "controlType": 5,
      "decimals": 0,
      "decimalsFieldId": ""
    },
    {
      "id": "Adress",
      "fieldId": "U004",
      "dataType": "string",
      "label": "Adres",
      "length": 255,
      "controlType": 1,
      "decimals": 0,
      "decimalsFieldId": ""
    },
    {
      "id": "Totale_aanneemsom",
      "fieldId": "U005",
      "dataType": "decimal",
      "label": "Totale aanneemsom",
      "length": 26,
      "controlType": 1,
      "decimals": 10,
      "decimalsFieldId": ""
    }
];


/**
* Returns Data Studio schema
*
* @param {object} javaScript object containing the schema request parameters.
*
* @returns {array} javaScript object representing the schema for the given request.
*/
function getSchema(request) {

  return {schema: connectorJson};

};


/**
* Get Data
* Returns Data to Data Studio based on the request
*
* @param {object} request parameter contains user provided values and additional information 
* that can be used to complete the data request
* 
* @returns {array} javaScript object that contains the schema and data for the given request.
* returns tabular data that satisfies the given request. The schema for the tabular data is included in the response.
*/
function getData(request) {

  Logger.log("Request from Data Studio");
  Logger.log(request);

  // Set the url
  var url = 'theUrl';
  return url;

  // empty arrays for data
  var dataSchema = [];
  var data = [];
  var values = [];

  request.fields.forEach(function(field) {
    for (var i = 0; i < connectorJson.length; i++) {
      if (connectorJson[i].name === field.id) {
        dataSchema.push(connectorJson[i]);
        break;
      }
    }
  });

  // Fetch the data
  // include error handling
  try {
    var headers = {
      "Authorization": "Token "+ Utilities.base64Encode(<token><version>1</version><data>AB1AB2AB3AB4</data></token>)

    };

    var options = {
      "method" : "get",
      "headers" : headers 
    };
    var response = JSON.parse(UrlFetchApp.fetch(url,options));
  } catch(e) {
    throw new Error("DS_USER: Unable to fetch the location data. Please try again later.");
  }

  Logger.log("Response from API");
  Logger.log(response);

  // turn epoch timestamp into human readable date
 // var date = new Date(response.timestamp * 1000);
 // var dsDate = date.toISOString().slice(0,10).replace(/-/g,"");

  // select items from the response data to return to Data Studio
  dataSchema.forEach(function(field) {
    switch(field.id) {
      case 'Jaartal':
        values.push(response.Jaartal);
        break;
      case 'Projectcode':
        values.push(response.Project_code);
        break;
      case 'Projectomschrijving':
        values.push(response.Title);
        break;
      case 'Hoofdproject':
        values.push(response.Hoofdproject);
        break;
      case 'Verkooprelatie':
        values.push(response.Verkooprelatie);
        break;
       case 'Hoofdproject':
        values.push(response.Hoofdproject);
        break;
      case 'Projectgroep':
        values.push(response.Project_groep);
        break;
      case 'Start event /(tijd/)':
        values.push(response.Start);
        break;
      case 'Eind event /(tijd/)':
        values.push(response.End);
        break;
      case 'Code':
        values.push(response.Code);
        break;
      case 'Adres':
        values.push(response.Adress);
      case 'Totale aanneemsom':
        values.push(response.Totale_aanneemsom);
        break;
      default:
        values.push('');
    }
  });

  data.push({
    values: values
  });

  Logger.log("Schema returned to Data Studio");
  Logger.log(dataSchema);

  Logger.log("Data returned to Data Studio");
  Logger.log(data);

  return {
    schema: dataSchema,
    rows: data
  };

}


/**
* Authentication
*
* @returns {object} containing the authentication method used by the connector.
*/
function getAuthType() {

  var response = {
    "type": "USER_TOKEN"
  };

  return response;

}

Solution

  • The official Authentication guide explains how you can get the username and token from the user, store them in script properties, and then use them in your code. You will need to create the setCredentials(), isAuthValid(), and resetAuth() functions as well.