# GASでkintoneのレコードを更新

**URL:** <https://community.cybozu.dev/t/topic/9525>\
**Category:** kintone 開発相談\
**Created:** [2024 年 9 月 18 日午前 4:39 UTC](https://community.cybozu.dev/t/topic/9525 "2024-09-18T04:39:43Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Netlinks\_tenjiku](https://avatars.discourse-cdn.com/v4/letter/n/a698b9/32.png) [@Netlinks\_tenjiku](https://community.cybozu.dev/u/Netlinks_tenjiku)\
**Post date:** [2024 年 9 月 18 日午前 4:39 UTC](https://community.cybozu.dev/t/topic/9525/1 "2024-09-18T04:39:43Z")

</div>

お世話になっております。  
以下のGASをwebhookで起動させ、以下の処理を実装したいと考えております。

1.kintoneの添付ファイルを、GoogleDriveの指定のフォルダに保存  
2.保存したファイルのURLを、トリガーとなったレコードの文字列フィールド「Driveリンク」にセットしたい（上書き更新）

コードは以下を参考にしております。

> **[GASでkintoneの添付ファイルをGoogleDriveに保存する](https://zenn.dev/juridon/articles/bce05edae25e29)**

現在、Driveに保存して、そのURLを取得するところまではうまくいっています。しかし、レコードが更新されず、新規作成されてしまいます。  
エラーを確認すると、302のエラーコードで、リダイレクトが生じているようです。  
どこをどう修正してよいかわからず、行き詰っています。  
ご教示いただけますと幸いです。

```javascript

// 定数の定義
const KINTONE_API_TOKEN = 'APITOKEN'; // kintoneのAPIトークン
const KINTONE_APP_ID = 2167; // kintoneアプリID
const GOOGLE_DRIVE_FOLDER_ID = 'xxxxx'; // Google DriveフォルダID
const KINTONE_API_URL_FILE = 'https://subdomein.cybozu.com/k/v1/file.json'; // kintoneファイルAPIのURL
const KINTONE_API_URL_RECORD = 'https://subdomein.cybozu.com/k/v1/record.json'; // kintoneレコードAPIのURL

function doPost(e) {
  try {
    // Webhookから送られてきたデータを解析
    const data = JSON.parse(e.postData.contents);
    
    // 必要な情報の検証
    if (!data.record || !data.record['出力pdf'] || !data.record['出力pdf'].value[0]) {
      throw new Error('Invalid data received from webhook');
    }
    
    const fileKey = data.record['出力pdf'].value[0].fileKey; // kintoneのファイルキー
    const recordId = data.record.$id.value; // kintoneのレコードID
    
    Logger.log(`App ID: ${KINTONE_APP_ID}`);
    Logger.log(`Record ID: ${recordId}`);
    Logger.log(`File Key: ${fileKey}`);
    
    // kintoneからファイルを取得
    const fileBlob = getKintoneFile(fileKey);
    
    if (fileBlob) {
      // Google Driveにアップロード
      const fileName = data.record['出力pdf'].value[0].name;
      const file = DriveApp.getFolderById(GOOGLE_DRIVE_FOLDER_ID).createFile(fileBlob).setName(fileName);
      
      // アップロードされたファイルのURLを取得
      const fileUrl = file.getUrl();
      
      // kintoneにDriveリンクを更新
      const updateSuccess = updateKintoneRecord(recordId, fileUrl);
      
      if (updateSuccess) {
        return ContentService.createTextOutput(JSON.stringify({ status: 'success', fileUrl: fileUrl }))
          .setMimeType(ContentService.MimeType.JSON);
      } else {
        return ContentService.createTextOutput(JSON.stringify({ status: 'error', message: 'Failed to update kintone record' }))
          .setMimeType(ContentService.MimeType.JSON);
      }
    } else {
      return ContentService.createTextOutput(JSON.stringify({ status: 'error', message: 'File not found' }))
        .setMimeType(ContentService.MimeType.JSON);
    }
  } catch (error) {
    Logger.log(`Exception: ${error.toString()}`);
    return ContentService.createTextOutput(JSON.stringify({ status: 'error', message: error.toString() }))
      .setMimeType(ContentService.MimeType.JSON);
  }
}

// kintoneからファイルを取得する関数
function getKintoneFile(fileKey) {
  const kintoneApiUrl = `${KINTONE_API_URL_FILE}?fileKey=${fileKey}`;
  
  const headers = {
    'X-Cybozu-API-Token': KINTONE_API_TOKEN,
  };

  const options = {
    method: 'get',
    headers: headers,
    muteHttpExceptions: true
  };
  
  try {
    const response = UrlFetchApp.fetch(kintoneApiUrl, options);
    
    Logger.log(`File fetch response code: ${response.getResponseCode()}`);
    Logger.log(`File fetch response: ${response.getContentText()}`);
    
    if (response.getResponseCode() === 200) {
      return response.getBlob();
    } else {
      Logger.log(`Error fetching file: ${response.getContentText()}`);
      return null;
    }
  } catch (error) {
    Logger.log(`Exception fetching file: ${error.toString()}`);
    return null;
  }
}

// kintoneのレコードを更新する関数
function updateKintoneRecord(recordId, fileUrl) {
  const postData = {
    app: KINTONE_APP_ID,
    id: recordId,
    record: {
      'Driveリンク': {
        value: fileUrl
      }
    }
  };

  const headers = {
    'X-Cybozu-API-Token': KINTONE_API_TOKEN,
    'Content-Type': 'application/json'
  };
  
  const options = {
    method: 'post', // POSTメソッドを使用
    headers: headers,
    muteHttpExceptions: true,
    payload: JSON.stringify(postData)
  };
  
  try {
    const response = UrlFetchApp.fetch(KINTONE_API_URL_RECORD, options);
    
    Logger.log(`Record update response code: ${response.getResponseCode()}`);
    Logger.log(`Record update response: ${response.getContentText()}`);
    
    if (response.getResponseCode() === 200) {
      Logger.log(`Successfully updated kintone record with Drive link: ${fileUrl}`);
      return true;
    } else {
      Logger.log(`Error updating kintone record: ${response.getContentText()}`);
      return false;
    }
  } catch (error) {
    Logger.log(`Exception updating kintone record: ${error.toString()}`);
    return false;
  }
}

```

---

<div class="post-metadata">

**Author:** ![lemon\_sour](https://sea1.discourse-cdn.com/flex015/user_avatar/community.cybozu.dev/lemon_sour/32/1469_2.png) [@lemon\_sour](https://community.cybozu.dev/u/lemon_sour)\
**Post date:** [2024 年 9 月 23 日午前 12:59 UTC](https://community.cybozu.dev/t/topic/9525/2 "2024-09-23T00:59:38Z")

</div>

updateKintoneRecord関数内にあるPostメソッドをPutにして、GASを再デプロイすればいきませんか？ レコードの更新はPostではなくPutのはずです。

参考  
[1件のレコードを更新する - cybozu developer network](https://cybozu.dev/ja/kintone/docs/rest-api/records/update-record/)

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/flex015/uploads/cybozu/original/1X/d5c841c3c5a6cb66eed514001c1b45147c9e1f4f.png) [@system](https://community.cybozu.dev/u/system)\
**Post date:** [2024 年 9 月 26 日午前 2:55 UTC](https://community.cybozu.dev/t/topic/9525/3 "2024-09-26T02:55:41Z")

</div>

このトピックはベストアンサーに選ばれた返信から 3 日が経過したので自動的にクローズされました。新たに返信することはできません。
