/* 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 => new Promise((resolve, reject) => { Papa.parse(csvString, { download: false, worker: true, header: true, dynamicTyping: true, complete: (results: ParseResult) => { // ヘッダーがCSVTypeFieldsと一致しない場合はエラーを返す if (!equals(results.meta.fields ?? [], CSVTypeFields)) { reject(new Error("Invalid CSV format")); } resolve(results.data); }, error: (error: Error) => { reject(error); }, }); });