kintone: Update Record

kintone: レコード更新

This item updates values of a record in a Kintone App.

Auto Step icon
Basic Configs
Step Name
Note
Configs for this Auto Step
conf_auth
C1: Authorization Setting in which API Token is set *
conf_basic
C2: Basic Auth Setting (required if enabled on Kintone)
conf_domain
C3: Domain (such as xxxxx.kintone.com or xxxxx.cybozu.com) *
conf_guestSpaceId
C4: Guest Space ID (required if the App is in a Guest Space)
conf_appId
C5: App ID *
conf_recordId
C6: Record ID *
conf_fieldCode1
C7F: Field Code 1
conf_fieldValue1
C7V: New Value 1#{EL}
conf_fieldCode2
C8F: Field Code 2
conf_fieldValue2
C8V: New Value 2#{EL}
conf_fieldCode3
C9F: Field Code 3
conf_fieldValue3
C9V: New Value 3#{EL}
conf_fieldCode4
C10F: Field Code 4
conf_fieldValue4
C10V: New Value 4#{EL}
conf_fieldCode5
C11F: Field Code 5
conf_fieldValue5
C11V: New Value 5#{EL}
conf_fieldCode6
C12F: Field Code 6
conf_fieldValue6
C12V: New Value 6#{EL}
conf_fieldCode7
C13F: Field Code 7
conf_fieldValue7
C13V: New Value 7#{EL}

Notes

  • To get an API Token, open the Settings of the App and click “API Token” in the App Settings tab on Kintone.

    Click “Generate”, select Permissions (“Edit records” permission is required), and click “Save”.

    Do not forget to click “Update App” to apply the update.
  • Guest Space ID (only when the Kintone App is in a guest space) and App ID can be confirmed in the API Token settings on Kintone.
  • Supported field types are: Text, Number, Text area, Rich text, Radio button, Drop-down, Link, Date, Time, Date and time.
  • Each value must be set in the data format that matches its field type. For example, to update a value in the Date and time field, the input must be something like 2015-03-17T10:20:00Z. For more details, see the Kintone Reference.

Capture

See also

Script (click to open)
  • An XML file that contains the code below is available to download
    • kintone-record-update.xml (C) Questetra, Inc. (MIT License)
    • If you are using Professional, you can modify the contents of this file and use it as your own add-on auto step


const FIELD_NUM = 7; // 扱えるフィールドの数

main();
function main() {
    //// == 工程コンフィグ・ワークフローデータの参照 / Config & Data Retrieving ==
    const auth = configs.get("conf_auth");
    const basic = configs.get("conf_basic");
    const domain = configs.get("conf_domain");
    const guestSpaceId = configs.get("conf_guestSpaceId");
    const appId = configs.get("conf_appId");
    const recordId = retrieveRecordId();

    const apiToken = httpClient.getOAuth2Token(auth);
    const recordObj = retrieveRecordContent();

    //// == 演算 / Calculating ==
    const apiUri = determineApiUri(domain, guestSpaceId);
    updateRecord(apiUri, apiToken, basic, appId, recordId, recordObj);
}

/**
  * config からレコード ID を読み出す
  * @return {Stromg} recordId  レコード ID
  */
function retrieveRecordId() {
    const recordIdDef = configs.getObject("conf_recordId");
    let recordId = configs.get("conf_recordId");
    if (recordIdDef !== null) {
        recordId = engine.findData(recordIdDef);
    }
    return recordId;
}

/**
  * configからレコード情報(フィールドコードとフィールドの値)を読み出し、JSON オブジェクトを返す
  * レコード情報が空の場合はエラーとする
  * @return {Object} recordObj  レコード情報の JSON オブジェクト
  */
function retrieveRecordContent() {
    const recordObj = {};
    for (let i = 0; i < FIELD_NUM; i++) {
        const fieldCodeConfigName = `conf_fieldCode${i + 1}`;
        const fieldValueConfigName = `conf_fieldValue${i + 1}`;

        const fieldCode = configs.get(fieldCodeConfigName);
        if (fieldCode === "" || fieldCode === null) { // フィールドコードが空
            continue;
        }
        if (recordObj[fieldCode] !== undefined) { // フィールドコードの指定が重複
            throw "The same Field Code is set multiple times.";
        }

        let fieldValue = configs.get(fieldValueConfigName);
        if (fieldValue === "" || fieldValue === null) { // 値が空
            fieldValue = null;
        }
        recordObj[fieldCode] = {
            "value": fieldValue
        };
    }
    if (Object.keys(recordObj).length === 0) { // レコード情報が空
        throw "No field to update is set.";
    }
    return recordObj;
}

/**
  * kintone REST API のレコード追加の URI を決定する
  * ドメインが空、または kintone のドメインとして不正な文字列であればエラーとする
  * ゲストスペース ID が不正な文字列であればエラーとする
  * @param {String} domain  ドメイン
  * @param {String} guestSpaceId  ゲストスペース ID
  * @return {String} apiUri  API の URI
  */
function determineApiUri(domain, guestSpaceId) {
    if (domain === "" || domain === null) {
        throw "Domain is empty.";
    }
    const domainReg = new RegExp('^[0-9a-zA-Z-]{3,32}.(?:kintone.com|cybozu.com)$');
    if (!domainReg.test(domain)) {
        throw "Invalid Kintone domain.";
    }
    let apiUri = "";
    if (guestSpaceId === "" || guestSpaceId === null) {
        apiUri = `https://${domain}/k/v1/record.json`;
    } else {
        if (!isValidId(guestSpaceId)) {
            throw "Invalid Guest Space ID.";
        }
        apiUri = `https://${domain}/k/guest/${guestSpaceId}/v1/record.json`;
    }
    return apiUri;
}

/**
  * kintone REST API にレコード更新の PUT リクエストを送信する
  * アプリ ID、レコード ID が空、または不正な文字列であればエラーとする
  * @param {String} apiUri  API の URI
  * @param {String} apiToken  API トークン
  * @param {String} basic  Basic 認証設定
  * @param {String} appId  アプリ ID
  * @param {String} recordId  レコード ID
  * @param {Object} recordObj  レコード情報の JSON オブジェクト
  */
function updateRecord(apiUri, apiToken, basic, appId, recordId, recordObj) {
    if (appId === "" || appId === null) {
        throw "App ID is empty.";
    }
    if (!isValidId(appId)) {
        throw "Invalid App ID.";
    }
    if (recordId === "" || recordId === null) {
        throw "Record ID is empty.";
    }
    if (!isValidId(recordId)) {
        throw "Invalid Record ID.";
    }
    const body = {
        "app": appId,
        "id": recordId,
        "record": recordObj
    };
    let request = httpClient.begin()
        .header("X-Cybozu-API-Token", apiToken)
        .body(JSON.stringify(body), "application/json; charset=UTF-8");
    if (basic !== "" && basic !== null) {
        request = request.authSetting(basic);
    }
    //when error thrown
    const response = request.put(apiUri);
    const responseJson = response.getResponseAsString();
    const status = response.getStatusCode();
    if (status >= 300) {
        engine.log(`API URI: ${apiUri}`);
        engine.log(`Request Body: ${JSON.stringify(body)}`);
        const accessLog = `---PUT request--- ${status}\n${responseJson}\n`;
        engine.log(accessLog);
        throw `Failed to update record. status: ${status}`;
    }
}

/**
  * ID が有効か(自然数か)を判定する
  * @param {String} idString  ID の文字列
  * @return {Boolean}  有効な ID かどうか
  */
function isValidId(idString) {
    const idReg = new RegExp('^[1-9][0-9]*$');
    return idReg.test(idString);
}
  

1 thought on “kintone: Update Record”

  1. Pingback: Using kintone from Workflow – Questetra Support

Comments are closed.

%d bloggers like this: