湯本 開 363f12f86f Merged PR 774: 画面実装(csv読み込み部分切り出し)
## 概要
[タスク 3754: 画面実装(csv読み込み部分切り出し)](https://paruru.nds-tyo.co.jp:8443/tfs/ReciproCollection/fa4924a4-d079-4fab-9fb5-a9a11eb205f0/_workitems/edit/3754)

- CSVファイルの内容を入力として、JSONに変換する処理&テストを実装
- 画面実装時の想定としては、以下の流れと想定しており、本Taskの範囲は1のみ
  1. csv->jsonへパースが出来るか?(csvの形式として合っていて読み込み可能か?)
  2. json内の各パラメータは問題ないか?(データの制限や組み合わせは問題ないか?)
- 使い方を示す & 動作確認のために、client側でもテストを実施できるよう修正(※pipelineでは実行されない)

## レビューポイント
- テストケースを見て、使い方は分かるか
- CSVの形式自体が想定とズレていた場合は入力を弾く必要がある想定だが、間違っていないか
- 利用ライブラリはメジャーかつ便利そうなものを選定したが、問題なさそうか

## 動作確認状況
- npm run testを通過
2024-02-28 09:03:27 +00:00

58 lines
1.5 KiB
TypeScript

/* eslint-disable @typescript-eslint/naming-convention */
import Papa, { ParseResult } from "papaparse";
export type CSVType = {
name: string | null;
email: string | null;
role: number | null;
author_id: string | null;
auto_renew: number | null;
notification: number;
encryption: number | null;
encryption_password: string | null;
prompt: number | null;
};
// CSVTypeのプロパティ名を文字列の配列で定義する
const CSVTypeFields: (keyof CSVType)[] = [
"name",
"email",
"role",
"author_id",
"auto_renew",
"notification",
"encryption",
"encryption_password",
"prompt",
];
// 2つの配列が等しいかどうかを判定する
const equals = (lhs: string[], rhs: string[]) => {
if (lhs.length !== rhs.length) return false;
for (let i = 0; i < lhs.length; i += 1) {
if (lhs[i] !== rhs[i]) return false;
}
return true;
};
/** CSVファイルをCSVType型に変換するパーサー */
export const parseCSV = async (csvString: string): Promise<CSVType[]> =>
new Promise((resolve, reject) => {
Papa.parse<CSVType>(csvString, {
download: false,
worker: true,
header: true,
dynamicTyping: true,
complete: (results: ParseResult<CSVType>) => {
// ヘッダーがCSVTypeFieldsと一致しない場合はエラーを返す
if (!equals(results.meta.fields ?? [], CSVTypeFields)) {
reject(new Error("Invalid CSV format"));
}
resolve(results.data);
},
error: (error: Error) => {
reject(error);
},
});
});