建立社群連接器

建立社群連結器的步驟如下:

  1. 建立新的 Apps Script 專案。
  2. 編寫連接器程式碼。
  3. 完成專案資訊清單。

建立新的 Apps Script 專案

前往 Google Apps Script 建立新專案。Apps Script 會為您建立預設指令碼。您可以移除 myFunction 函式,並重新命名專案。(進一步瞭解 Apps Script)

編寫連接器程式碼

每個連接器都必須定義一組特定函式。主機應用程式 (例如 Looker Studio) 會執行這些函式。連接器應處理傳入要求,並按照社群連接器 API 參考資料所述方式回應。如果在開發程式碼時遇到問題,請參閱偵錯指南尋求協助。

在 getAuthType() 中定義驗證類型

這個函式會呼叫,以識別第三方服務使用的驗證方法。詳情請參閱 getAuthType() 參考資料。目前支援的驗證方法列於AuthType參考資料

舉例來說,下列連接器不需要驗證:

npm-downloads/src/auth.js
var cc = DataStudioApp.createCommunityConnector();

// https://developers.google.com/datastudio/connector/reference#getauthtype
function getAuthType() {
  var AuthTypes = cc.AuthType;
  return cc
    .newAuthTypeResponse()
    .setAuthType(AuthTypes.NONE)
    .build();
}

如果資料來源需要 OAuth 2.0 驗證,請參閱 OAuth 2.0 驗證指南,並在連結器中新增其他必要函式。

透過 getConfig() 定義設定

系統會呼叫 getConfig() 函式,取得連接器的設定,包括連接器所需的使用者提供值。詳情請參閱 getConfig() 參考資料。

Looker Studio 會根據 getConfig() 提供的回應,顯示連接器設定畫面。如要查看支援的設定元素,請參閱 ConfigType 參考資料

如果資料來源需要日期做為參數,請呼叫 config.setDateRangeRequired(true)。如需詢問條件式或動態設定問題,請參閱逐步設定

以下是連接器的範例,使用者必須輸入 npm 套件名稱代碼。資訊和輸入欄位是在 getConfig() 函式中定義:

npm-downloads/src/main.js
// https://developers.google.com/datastudio/connector/reference#getconfig
function getConfig() {
  var config = cc.getConfig();

  config
    .newInfo()
    .setId('instructions')
    .setText(
      'Enter npm package names to fetch their download count. An invalid or blank entry will revert to the default value.'
    );

  config
    .newTextInput()
    .setId('package')
    .setName(
      'Enter a single package name or multiple names separated by commas (no spaces!)'
    )
    .setHelpText('e.g. "googleapis" or "package,somepackage,anotherpackage"')
    .setPlaceholder(DEFAULT_PACKAGE)
    .setAllowOverride(true);

  config.setDateRangeRequired(true);

  return config.build();
}

使用 getSchema() 定義欄位

系統會呼叫此函式,以取得指定要求的結構定義。getConfig() 函式定義的任何設定參數都會在 request 引數中提供。詳情請參閱getSchema()參考資料

視連結器的資料來源和使用者提供的設定而定,結構定義可能是固定的,也可能需要在要求時動態提供。

舉例來說,如果連接器是根據報表 ID 擷取報表資料,系統可能無法事先得知該報表傳回的資料,以及架構。在這種情況下,getSchema() 可能需要擷取資料,且必須計算結構定義。

npm-downloads/src/main.js
function getFields() {
  var fields = cc.getFields();
  var types = cc.FieldType;
  var aggregations = cc.AggregationType;

  fields
    .newDimension()
    .setId('packageName')
    .setName('Package')
    .setType(types.TEXT);

  fields
    .newDimension()
    .setId('day')
    .setName('Date')
    .setType(types.YEAR_MONTH_DAY);

  fields
    .newMetric()
    .setId('downloads')
    .setName('Downloads')
    .setType(types.NUMBER)
    .setAggregation(aggregations.SUM);

  return fields;
}

// https://developers.google.com/datastudio/connector/reference#getschema
function getSchema(request) {
  return {schema: getFields().build()};
}

使用 getData() 擷取及傳回資料

系統會呼叫這個函式,以取得指定要求的資料。getConfig() 函式定義的任何設定參數都會在 request 引數中提供。詳情請參閱getData()參考資料

getData() 要求中的下列參數需要特別注意:

  • lastRefresh
    lastRefresh 代表時間戳記,標示最近一次要求重新整理資料的時間。您應該可以使用 new Date(timestampString) 剖析值。如果您使用 Apps Script Cache Service 或任何其他快取方法,lastRefresh 時間戳記可協助您判斷是否要向資料來源發出新的擷取要求,或是從快取提供資料。

  • dateRange
    如果 dateRangeRequired 設為 getConfig() 中的 true,每個 getData() 呼叫都會在要求中包含所選日期範圍。詳情請參閱「使用日期範圍」。

以下範例會根據連入要求擷取資料,並傳回套件統計資料:

npm-downloads/src/main.js
// https://developers.google.com/datastudio/connector/reference#getdata
function getData(request) {
  request.configParams = validateConfig(request.configParams);

  var requestedFields = getFields().forIds(
    request.fields.map(function(field) {
      return field.name;
    })
  );

  try {
    var apiResponse = fetchDataFromApi(request);
    var normalizedResponse = normalizeResponse(request, apiResponse);
    var data = getFormattedData(normalizedResponse, requestedFields);
  } catch (e) {
    cc.newUserError()
      .setDebugText('Error fetching data from API. Exception details: ' + e)
      .setText(
        'The connector has encountered an unrecoverable error. Please try again later, or file an issue if this error persists.'
      )
      .throwException();
  }

  return {
    schema: requestedFields.build(),
    rows: data
  };
}

/**
 * Gets response for UrlFetchApp.
 *
 * @param {Object} request Data request parameters.
 * @returns {string} Response text for UrlFetchApp.
 */
function fetchDataFromApi(request) {
  var url = [
    'https://api.npmjs.org/downloads/range/',
    request.dateRange.startDate,
    ':',
    request.dateRange.endDate,
    '/',
    request.configParams.package
  ].join('');
  var response = UrlFetchApp.fetch(url);
  return response;
}

/**
 * Parses response string into an object. Also standardizes the object structure
 * for single vs multiple packages.
 *
 * @param {Object} request Data request parameters.
 * @param {string} responseString Response from the API.
 * @return {Object} Contains package names as keys and associated download count
 *     information(object) as values.
 */
function normalizeResponse(request, responseString) {
  var response = JSON.parse(responseString);
  var package_list = request.configParams.package.split(',');
  var mapped_response = {};

  if (package_list.length == 1) {
    mapped_response[package_list[0]] = response;
  } else {
    mapped_response = response;
  }

  return mapped_response;
}

/**
 * Formats the parsed response from external data source into correct tabular
 * format and returns only the requestedFields
 *
 * @param {Object} parsedResponse The response string from external data source
 *     parsed into an object in a standard format.
 * @param {Array} requestedFields The fields requested in the getData request.
 * @returns {Array} Array containing rows of data in key-value pairs for each
 *     field.
 */
function getFormattedData(response, requestedFields) {
  var data = [];
  Object.keys(response).map(function(packageName) {
    var package = response[packageName];
    var downloadData = package.downloads;
    var formattedData = downloadData.map(function(dailyDownload) {
      return formatData(requestedFields, packageName, dailyDownload);
    });
    data = data.concat(formattedData);
  });
  return data;
}

填寫專案資訊清單

資訊清單檔案包含部署及在 Looker Studio 中使用社群連結器時所需的連結器資訊。

如要在 Apps Script 開發環境中編輯資訊清單檔案,請按一下「View」選單,然後點選「Show manifest file」。系統會建立新的appsscript.json資訊清單檔案。

更新資訊清單,加入下列資料:

npm-downloads/src/appsscript.json
{
  "dependencies": {
    "libraries": []
  },
  "dataStudio": {
    "name": "npm Downloads",
    "logoUrl": "https://raw.githubusercontent.com/npm/logos/master/npm%20square/n-64.png",
    "company": "Google Data Studio Developer Relations",
    "companyUrl": "https://developers.google.com/datastudio/",
    "addonUrl": "https://github.com/googledatastudio/community-connectors/tree/master/npm-downloads#readme",
    "supportUrl": "https://github.com/googledatastudio/community-connectors/issues",
    "description": "Get npm package download counts.",
    "sources": ["npm"],
    "templates": {
      "default": "1twu0sHjqR5dELAPyGJcw4GS3-D0_NTrQ"
    }
  },
  "oauthScopes": [
    "https://www.googleapis.com/auth/script.external_request"
  ]
}

如要瞭解 Looker Studio 資訊清單的詳細資料,請參閱資訊清單參考資料

後續步驟

下一步是部署社群連接器