📝
google app script から kintone のレコードを削除(複数)
kintoneのデータを、クエリを使って複数件削除するスクリプトです。
はじめに
以下の環境で動作しています。
- google app script … Chrome V8ランタイム利用
- kintone … クラウド最新版(2025年1月時点)
用意するもの
例によって、google app script → プロジェクトの設定 → スクリプトプロパティ に、以下3つのプロパティを作成します。
それぞれ取得元のアプリにあわせてください。
プロパティ名 | 値(例) | 備考 |
---|---|---|
subdomain | myDomain | アドレス欄https://domainName.cybozu.comにあるdomainName部分 |
appId | 123 | レコード更新先のアプリID |
appToken | ABCDEFG1234567 | 削除対象レコードのあるアプリで作成したAPIトークン。 「レコード削除」の権限が必要。 |
スクリプト
deleteRecords.gs
/**
* サンプルスクリプト
*/
function sampleScript() {
const deleteIDs = [
1,
2,
3,
10,
23,
50,
]
const resp = deleteRecords(deleteIDs)
Logger.log(resp)
}
/**
* スクリプトプロパティに設定したアプリのレコードを複数件削除
*/
function deleteRecords(recordIDs) {
const subDomain = scriptProperties.getProperty('subdomain')
const appId = Number(scriptProperties.getProperty('appId'))
const appToken = scriptProperties.getProperty('appToken')
recordIDs.forEach((ID)=>{
if (!Number.isInteger(ID)) {
throw new Error('配列に整数値以外が検出されました。')
}
})
const url = `https://${subDomain}.cybozu.com/k/v1/records.json`;
const options = {
method: 'DELETE',
headers: {
'X-Cybozu-API-Token': appToken,
'Content-Type': 'application/json',
},
muteHttpExceptions: true,
payload: JSON.stringify({
app: appId,
ids: recordIDs,
// revisions: [9,8,15,21,3,6,11,8,8,2],
}),
};
try {
const resp = UrlFetchApp.fetch(url, options);
if (resp.getResponseCode()!==200) {
throw new Error(`レコード削除エラー:\n HTTPステータス:${resp.getResponseCode()}\n レスポンス :${resp.toString()}`);
}
return JSON.parse(resp.getContentText()); // 削除の場合は通常は空文字列が返される
} catch (error) {
throw new Error(error.message);
}
}
説明
削除レコードを指定
part of deleteRecords.gs
const deleteIDs = [
1,
2,
3,
10,
23,
50,
]
複数件も同時削除できますが、1リクエストにつき最大100件までの制限があります。
スクリプトプロパティから秘匿した設定を取得
part of deleteRecords.gs
const subDomain = scriptProperties.getProperty('subdomain')
const appId = Number(scriptProperties.getProperty('appId'))
const appToken = scriptProperties.getProperty('appToken')
見慣れた三連星。いつも通りです。
パラメータ・リクエストヘッダ・リクエストボディの作成
part of deleteRecords.gs
const url = `https://${subDomain}.cybozu.com/k/v1/records.json`;
const options = {
method: 'DELETE',
headers: {
'X-Cybozu-API-Token': appToken,
'Content-Type': 'application/json',
},
muteHttpExceptions: true,
payload: JSON.stringify({
app: appId,
ids: recordIDs,
// revisions: [9,8,15,21,3,6,11,8,8,2],
}),
};
リクエストの肝になる部分です。
payload
にrevisions
を追加することでより厳密な削除(寸分早く、別のユーザーが内容更新→保存していたら削除できない、等)を設ける事ができますが、そうでない場合は指定不要です。
リクエストする
part of deleteRecords.gs
try {
const resp = UrlFetchApp.fetch(url, options);
if (resp.getResponseCode()!==200) {
throw new Error(`レコード削除エラー:\n HTTPステータス:${resp.getResponseCode()}\n レスポンス :${resp.toString()}`);
}
return JSON.parse(resp.getContentText()); // 削除の場合は通常は空文字列が返される
} catch (error) {
throw new Error(error.message);
}
GASスクリプト標準のHTTPリクエストUrlFetchApp.fetch
を使って外部(kintone)にHTTPリクエストします。
レスポンスコードが200以外はエラーになるので、その場合にはエラーをthrow
するようにしています。
Discussion