Data Studio - коннектор сообщества - как добавить токен пользователя? - PullRequest
0 голосов
/ 01 мая 2020

Я хочу подключиться к REST API. Это прекрасно работает с Google листами и скриптами. Но теперь я не знаю, как я могу вставить требуемый токен. Это должно быть в заголовке GetRequest, поэтому я попробовал этот код. Но когда я запускаю через манифест файл, я получаю сообщение об ошибке:

Произошла ошибка, вызванная этим соединителем.

Мой сценарий

Как видите, я пытаюсь передать токен в getData (). Соми знает решение?

/**
 * 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;

}

1 Ответ

0 голосов
/ 03 мая 2020

Официальное руководство Аутентификация объясняет, как вы можете получить username и token от пользователя, сохранить их в свойствах скрипта, а затем использовать их в своем коде. Вам также необходимо создать функции setCredentials(), isAuthValid() и resetAuth().

...