星期一, 8月 18, 2025

[GAS] Properties Service

Properties service 可以用來儲存 key-value 資料且資料型態為字串,有三種方式,分別為
  • Script Properties
  • User Properties
  • Document Properties

官方文章-Properties Service 上的分析表
該分析表內關於 Script Properties 說明,應用範圍是專案全域使用,該說明舉例是提到可以拿存放外部 Database 使用者名稱、密碼,認知就算是存放機敏資料 (連線字串、Token 之類),因為找不到官方文章有提到會特別處理,所以特別去研究看看,結論是假如只有該專案只有個人使用就適合,萬一該專案分享給多人就不適合,比把機敏資料明碼放在 gs 檔案內好而已,該篇文章 How to Store Secrets in Google Apps Script 內有張流程圖可以提供思考方向,最好還是放上 GCP 保護還可以分享給多專案使用

GUI 操作

Script Properties 是三種 Property 中,唯一有 GUI 可以手動操作

語法操作

function PropertiesServiceDemo() {
  
  // 取得 ScriptProperties
  let scriptProperties = PropertiesService.getScriptProperties();

  // 新增 TOKEN Property
  scriptProperties.setProperty('TOKEN', '123456789');

  // 新增多個 Property
  scriptProperties.setProperties({
    'Key-1': 'Value1',
    'Key-2': 'Value2'
  });

  // 該 Key 已經存在的話,即為更新目前 Property 值
  scriptProperties.setProperty('TOKEN', 'ABCDEFG');

  // 顯示目前 Property 資料
  let properties = scriptProperties.getProperties();
  for (let key in properties) {
    Logger.log(`Key: ${key}, Value: ${properties[key]}`);
  }  

  // 刪除 Property
  scriptProperties.deleteProperty('Key-2');
}

執行結果


沒有留言:

張貼留言