LoginSignup
0
0

Promise型データの処理対応(csv出力例)

Last updated at Posted at 2023-10-24

はじめに

kintoneでのcsv出力を記載する。
kintoneの場合、データを取得する場合、kintone apiを使用するが、非同期関数でその値はPromise型になる。そのデータを扱う場合、少し慣れが必要なため、動くであろう例を記載する。

処理内容

ボタンクリックでcsv出力する
1.データ取得をidより行うにあたり、にkintone apiを使用する。
その時、queryで、idを絞る例を記載する。
kintone apiで取得するにあたりデータは非同期関数でpromise型になる。
その結果を直接変数に格納することはできないため、await直後に処理を行う。
2.dataを取得後、csvデータ取得、ダウンロードという流れになる。

kintoneでのcsv出力のjavascript例


// 仮にボタンのIDが 'downloadButton' であると仮定
document.getElementById('downloadButton').addEventListener('click', handleButtonClick);



const ids = [456, 457, 458];
const queryString = `$id in (${ids.join(", ")})`;

const body = {
    app: 123, // ここにアプリIDをセット
    query: queryString
};


async function fetchKintoneRecords() {
    try {
        const data = await kintone.api(kintone.api.url('/k/v1/records', true), 'GET', body);
        console.log(data);
    } catch (error) {
        console.error("Error fetching records:", error);
    }
}

function convertToCSV(records) {
  // ヘッダーの作成
  const header = ['fieldA', 'fieldB', 'fieldC'];
  const csv = records.map(record => {
      return [
          record['fieldA']['value'],
          record['fieldB']['value'],
          record['fieldC']['value']
      ].join(',');
  });
  
  return [header.join(',')].concat(csv).join('\n');
}


function downloadCSV(csv, filename) {
  const blob = new Blob([csv], { type: 'text/csv' });
  const url = window.URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.setAttribute('hidden', '');
  a.setAttribute('href', url);
  a.setAttribute('download', filename);
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}

async function handleButtonClick() {
  try {
      const data = await fetchKintoneRecords();
      const csv = convertToCSV(data.records);
      downloadCSV(csv, 'kintone_data.csv');
  } catch (error) {
      console.error("Error during button click handling:", error);
  }
}


注記点

csv出力箇所のconvertToCSV()、downloadCSV()はかなりノウハウ化されているのでここでは特に記載しない。
kintoneのquery使用時、データ取得後の処理について記載する。

queryで$id限定
${...}はテンプレートリテラル

const queryString = `$id in (${ids.join(",")})`;

ids = [1, 2, 3]の場合、ids.join(", ")は"1, 2, 3"という文字列を返す。
queryでin句を使用している。

データ取得後、そのデータを使用する
fetchKintoneRecords()にて、async await、ボタンクリック時に、その関数でasync、fetchKintoneRecords()使用時にawaitでdataを取得する。

async function fetchKintoneRecords() {
    try {
        const data = await kintone.api(kintone.api.url('/k/v1/records', true), 'GET', body);
        console.log(data);
    } catch (error) {
        console.error("Error fetching records:", error);
    }
}

async function handleButtonClick() {
  try {
      const data = await fetchKintoneRecords();
      const csv = convertToCSV(data.records);
      downloadCSV(csv, 'kintone_data.csv');
  } catch (error) {
      console.error("Error during button click handling:", error);
  }
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0