ttrpg-tools/src/components/utils/csv-loader.ts

30 lines
733 B
TypeScript
Raw Normal View History

2026-02-27 12:24:51 +08:00
import { parse } from 'csv-parse/browser/esm/sync';
/**
* CSV
*/
2026-02-27 12:38:09 +08:00
const csvCache = new Map<string, Record<string, string>[]>();
2026-02-27 12:24:51 +08:00
/**
* CSV
2026-02-27 12:38:09 +08:00
* @template T Record<string, string>
2026-02-27 12:24:51 +08:00
*/
2026-02-27 12:38:09 +08:00
export async function loadCSV<T = Record<string, string>>(path: string): Promise<T[]> {
2026-02-27 12:24:51 +08:00
if (csvCache.has(path)) {
2026-02-27 12:38:09 +08:00
return csvCache.get(path)! as T[];
2026-02-27 12:24:51 +08:00
}
const response = await fetch(path);
const content = await response.text();
const records = parse(content, {
columns: true,
comment: '#',
trim: true,
skipEmptyLines: true
});
2026-02-27 12:38:09 +08:00
const result = records as Record<string, string>[];
2026-02-27 12:24:51 +08:00
csvCache.set(path, result);
2026-02-27 12:38:09 +08:00
return result as T[];
2026-02-27 12:24:51 +08:00
}