30 lines
640 B
TypeScript
30 lines
640 B
TypeScript
|
|
import { parse } from 'csv-parse/browser/esm/sync';
|
||
|
|
import type { CardData } from '../types';
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 全局缓存已加载的 CSV 内容
|
||
|
|
*/
|
||
|
|
const csvCache = new Map<string, CardData[]>();
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 加载 CSV 文件
|
||
|
|
*/
|
||
|
|
export async function loadCSV(path: string): Promise<CardData[]> {
|
||
|
|
if (csvCache.has(path)) {
|
||
|
|
return csvCache.get(path)!;
|
||
|
|
}
|
||
|
|
|
||
|
|
const response = await fetch(path);
|
||
|
|
const content = await response.text();
|
||
|
|
const records = parse(content, {
|
||
|
|
columns: true,
|
||
|
|
comment: '#',
|
||
|
|
trim: true,
|
||
|
|
skipEmptyLines: true
|
||
|
|
});
|
||
|
|
|
||
|
|
const result = records as CardData[];
|
||
|
|
csvCache.set(path, result);
|
||
|
|
return result;
|
||
|
|
}
|