レコード一括取得の JavaScript コーディング例

目次

はじめに

レコードを一括取得する方法には、大きく 3 つの選択肢があり、利用ケースに応じて適切な方法を選択する必要があります。
それぞれの方法の特徴や使い分けについては、次の記事で紹介しています。
offset の制限値を考慮した kintone のレコード一括取得について

この記事では、上記記事で紹介した方法の JavaScript のコーディング例を紹介します。

共通事項

  • 各方法の getRecords() 関数を呼び出すサンプルコードでは、アプリストアの「 案件管理 (External link) 」アプリを利用しています。
  • フィールドコードは、フィールド名と同じ値に設定しています。

方法 1:レコード ID を利用する方法

複数のレコードを取得する API で、レコード ID(レコード番号)の昇順でソートを行い、ID 順にレコードを取得する方法です。

サンプルコード

レコードを取得する関数
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
 * get all records function by using record id sample program
 * Copyright (c) 2019 Cybozu
 *
 * Licensed under the MIT License
 * https://opensource.org/license/mit/
 */

/*
 * @param {Object} params
 *   - app {String}: アプリID(省略時は表示中アプリ)
 *   - filterCond {String}: 絞り込み条件
 *   - sortConds {Array}: ソート条件の配列
 *   - fields {Array}: 取得対象フィールドの配列
 * @return {Object} response
 *   - records {Array}: 取得レコードの配列
 */
const getRecords = (_params) => {
  const MAX_READ_LIMIT = 500;

  const params = _params || {};
  const app = params.app || kintone.app.getId();
  const filterCond = params.filterCond;
  const sortConds = params.sortConds || ['$id asc'];
  const fields = params.fields;
  let data = params.data;

  if (!data) {
    data = {
      records: [],
      lastRecordId: 0
    };
  }

  const conditions = [];
  const limit = MAX_READ_LIMIT;
  if (filterCond) {
    conditions.push(filterCond);
  }

  conditions.push('$id > ' + data.lastRecordId);

  const sortCondsAndLimit =
    ` order by ${sortConds.join(', ')} limit ${limit}`;
  const query = conditions.join(' and ') + sortCondsAndLimit;
  const body = {
    app: app,
    query: query
  };

  if (fields && fields.length > 0) {
    // $id で並び替えを行うため、取得フィールドに「$id」フィールドが含まれていなければ追加します
    if (fields.indexOf('$id') <= -1) {
      fields.push('$id');
    }
    body.fields = fields;
  }

  return kintone.api(kintone.api.url('/k/v1/records', true), 'GET', body).then((r) => {
    data.records = data.records.concat(r.records);
    if (r.records.length === limit) {
      // 取得レコードの件数が limit と同じ場合は、未取得のレコードが残っている場合があるので、getRecords を再帰呼び出して、残りのレコードを取得します
      data.lastRecordId = r.records[r.records.length - 1].$id.value;
      return getRecords({app: app, filterCond: filterCond, sortConds: sortConds, fields: fields, data: data});
    }
    delete data.lastRecordId;
    return data;
  });
};
getRecords 関数の呼び出し例
絞り込み条件・ソート条件・取得するフィールドを指定した場合

レコード ID を利用してレコードを取得する場合は、sortConds$id asc を追加してください。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
/*
 * call getRecords function sample program
 * Copyright (c) 2019 Cybozu
 *
 * Licensed under the MIT License
 * https://opensource.org/license/mit/
 */

// 次の query に一致するレコードを取得します
// 確度 in ("A") and 見込み時期 >= THIS_YEAR() and $id > 0 order by $id asc, 小計 desc, 会社名 asc limit 500
const params = {
  app: 1,
  filterCond: '確度 in ("A") and 見込み時期 >= THIS_YEAR()',
  // ソート条件は、「'フィールドコード ascまたはdesc'」という形式で指定します
  sortConds: ['$id asc', '小計 desc', '会社名 asc'],
  fields: ['レコード番号', '会社名', '先方担当者', '見込み時期', '確度', '製品名', '単価', 'ユーザー数', '小計']
};
getRecords(params).then((resp) => {
  console.log(resp);
});
アプリ ID を指定しない場合

アプリ ID を指定しない場合は、表示中のアプリのレコードを取得します。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
/*
 * call getRecords function sample program
 * Copyright (c) 2019 Cybozu
 *
 * Licensed under the MIT License
 * https://opensource.org/license/mit/
 */

// 次の query に一致するレコードを取得します
// $id > 0 order by $id asc limit 500
getRecords().then((resp) => {
  console.log(resp);
});

方法 2:カーソル API を利用する方法

カーソル API を使ってレコードを取得する方法です。

サンプルコード

レコードを取得する関数
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
 * get all records function by cursor id sample program
 * Copyright (c) 2019 Cybozu
 *
 * Licensed under the MIT License
 * https://opensource.org/license/mit/
 */

// カーソルを作成する
const postCursor = (_params) => {
  const MAX_READ_LIMIT = 500;

  const params = _params || {};
  const app = params.app || kintone.app.getId();
  const filterCond = params.filterCond;
  const sortConds = params.sortConds;
  const fields = params.fields;

  const conditions = [];
  if (filterCond) {
    conditions.push(filterCond);
  }

  const sortCondsAndLimit =
    (sortConds && sortConds.length > 0 ? ' order by ' + sortConds.join(', ') : '');
  const query = conditions.join(' and ') + sortCondsAndLimit;
  const body = {
    app: app,
    query: query,
    size: MAX_READ_LIMIT
  };
  if (fields && fields.length > 0) {
    body.fields = fields;
  }

  return kintone.api(kintone.api.url('/k/v1/records/cursor', true), 'POST', body).then((r) => {
    return r.id;
  });
};

// 作成したカーソルからレコードを取得する
const getRecordsByCursorId = (_params) => {
  const params = _params || {};
  const id = params.id;

  let data = params.data;

  if (!data) {
    data = {
      records: []
    };
  }

  const body = {
    id: id
  };
  return kintone.api(kintone.api.url('/k/v1/records/cursor', true), 'GET', body).then((r) => {
    data.records = data.records.concat(r.records);
    if (r.next) {
      return getRecordsByCursorId({id: id, data: data});
    }
    return data;
  });
};

/*
 * @param {Object} params
 *   - app {String}: アプリID(省略時は表示中アプリ)
 *   - filterCond {String}: 絞り込み条件
 *   - sortConds {Array}: ソート条件の配列
 *   - fields {Array}: 取得対象フィールドの配列
 * @return {Object} response
 *   - records {Array}: 取得レコードの配列
 */
const getRecords = (_params) => {
  return postCursor(_params).then((id) => {
    return getRecordsByCursorId({id: id});
  });
};
getRecords 関数の呼び出し例
絞り込み条件・ソート条件・取得するフィールドを指定した場合
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
/*
 * call getRecords function sample program
 * Copyright (c) 2019 Cybozu
 *
 * Licensed under the MIT License
 * https://opensource.org/license/mit/
 */

// 次の query に一致するレコードを取得します
// 確度 in ("A") and 見込み時期 >= THIS_YEAR() order by 小計 desc, 会社名 asc
const params = {
  app: 1,
  filterCond: '確度 in ("A") and 見込み時期 >= THIS_YEAR()',
  sortConds: ['小計 desc', '会社名 asc'],
  fields: ['レコード番号', '会社名', '先方担当者', '見込み時期', '確度', '製品名', '単価', 'ユーザー数', '小計'],
};
getRecords(params).then((resp) => {
  console.log(resp);
});
アプリ ID を指定しない場合

アプリ ID を指定しない場合は、表示中のアプリのレコードを取得します。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
/*
 * call getRecords function sample program
 * Copyright (c) 2019 Cybozu
 *
 * Licensed under the MIT License
 * https://opensource.org/license/mit/
 */

// query は ''(空白) で指定されます
getRecords().then((resp) => {
  console.log(resp);
});

方法 3:offset を利用する方法

複数のレコードを取得する API を使い、リクエストパラメーターの offset を指定して順次レコードを取得する方法です。

この方法は、次のどちらかに一致する場合に使用できます。

  • 取得対象のレコードが 10,000 件以内
  • 取得するレコードを 10,000 件以内に制限可能

offset の制限値を考慮した kintone のレコード一括取得についての基本的な考え方は offset の制限値を考慮した kintone のレコード一括取得について を参照してください。

サンプルコード

レコードを取得する関数
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
 * get all records function by using offset sample program
 * Copyright (c) 2019 Cybozu
 *
 * Licensed under the MIT License
 * https://opensource.org/license/mit/
 */

/*
 * @param {Object} _params
 *   - app {String}: アプリID(省略時は表示中アプリ)
 *   - filterCond {String}: 絞り込み条件
 *   - sortConds {Array}: ソート条件の配列
 *   - fields {Array}: 取得対象フィールドの配列
 *   - limit {Number}: レコードの取得件数(省略時は絞り込み条件に合うレコードを全件取得する)
 * @return {Object} response
 *   - records {Array}: 取得レコードの配列
 */
const getRecords = (_params) => {
  const MAX_READ_LIMIT = 500;

  const params = _params || {};
  const app = params.app || kintone.app.getId();
  const filterCond = params.filterCond;
  const sortConds = params.sortConds;
  const limit = params.limit || -1;
  const offset = params.offset || 0;
  const fields = params.fields;
  let data = params.data;

  if (!data) {
    data = {
      records: []
    };
  }

  let willBeDone = false;
  let thisLimit = MAX_READ_LIMIT;
  // getRecords 関数の呼び出し側で、レコードの取得件数を指定された場合は
  // 取得件数を満たせば終了するように willBeDone を true にする
  if (limit > 0) {
    if (thisLimit > limit) {
      thisLimit = limit;
      willBeDone = true;
    }
  }

  const conditions = [];
  if (filterCond) {
    conditions.push(filterCond);
  }

  const sortCondsAndLimit = (sortConds && sortConds.length > 0 ? ' order by ' + sortConds.join(', ') : '')
    + ' limit ' + thisLimit;
  const query = conditions.join(' and ') + sortCondsAndLimit + ' offset ' + offset;
  const body = {
    app: app,
    query: query
  };
  if (fields && fields.length > 0) {
    body.fields = fields;
  }
  return kintone.api(kintone.api.url('/k/v1/records', true), 'GET', body).then((resp) => {
    data.records = data.records.concat(resp.records);
    const _offset = resp.records.length;
    if (limit > 0 && limit < _offset) {
      willBeDone = true;
    }
    // 取得すべきレコードを取得したら終了する
    if (_offset < thisLimit || willBeDone) {
      return data;
    }
    // 取得すべきレコードが残っている場合は、再帰呼び出しで残りのレコードを取得する
    return getRecords({
      app: app,
      filterCond: filterCond,
      sortConds: sortConds,
      limit: limit - _offset,
      offset: offset + _offset,
      fields: fields,
      data: data
    });
  });
};
getRecords 関数の呼び出し例
絞り込み条件・ソート条件・取得するフィールドを指定する場合
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
/*
 * call getRecords function sample program
 * Copyright (c) 2019 Cybozu
 *
 * Licensed under the MIT License
 * https://opensource.org/license/mit/
 */

// 次の query に一致するレコードを取得します
// 確度 in ("A") and 見込み時期 >= THIS_YEAR() order by 小計 desc, 会社名 asc limit 500 offset 0
const params = {
  app: 1,
  filterCond: '確度 in ("A") and 見込み時期 >= THIS_YEAR()',
  sortConds: ['小計 desc', '会社名 asc'],
  fields: ['レコード番号', '会社名', '先方担当者', '見込み時期', '確度', '製品名', '単価', 'ユーザー数', '小計'],
};
getRecords(params).then((resp) => {
  console.log(resp);
});
アプリ ID を指定しない場合

アプリ ID を指定しない場合は、表示中のアプリのレコードを取得します。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
/*
 * call getRecords function sample program
 * Copyright (c) 2019 Cybozu
 *
 * Licensed under the MIT License
 * https://opensource.org/license/mit/
 */

// 次の query に一致するレコードを取得します
// limit 500 offset 0
getRecords().then((resp) => {
  console.log(resp);
});