建立社群連接器

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

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

建立新的 Apps Script 專案

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

編寫連接器程式碼

每個連接器都必須定義一組特定函式。託管應用程式 (例如 Looker Studio) 會執行這些函式。連接器應可處理傳入要求並回應,如 Community Connector 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() 參考資料。

根據 getConfig() 提供的回應,Looker Studio 會顯示連接器設定畫面。支援的設定元素列於 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 快取服務或任何其他快取方法,lastRefresh 時間戳記可協助您判斷是否要向資料來源提出新的擷取要求,或是提供來自快取的資料。

  • dateRange
    如果在 getConfig() 中將 dateRangeRequired 設為 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 資訊清單,請參閱資訊清單參考資料

後續步驟

下一步是部署社群連接器