refactor: csv loader
This commit is contained in:
parent
807ce5a406
commit
a409efaf95
|
|
@ -1,8 +1,8 @@
|
|||
import { customElement, noShadowDOM } from 'solid-element';
|
||||
import { createSignal, For, Show, createEffect, createMemo, createResource } from 'solid-js';
|
||||
import { parse } from 'csv-parse/browser/esm/sync';
|
||||
import { marked } from '../markdown';
|
||||
import { resolvePath } from '../utils';
|
||||
import { loadCSV } from './utils/csv-loader';
|
||||
|
||||
export interface TableProps {
|
||||
roll?: boolean;
|
||||
|
|
@ -15,9 +15,6 @@ interface TableRow {
|
|||
[key: string]: string;
|
||||
}
|
||||
|
||||
// 全局缓存已加载的 CSV 内容
|
||||
const csvCache = new Map<string, TableRow[]>();
|
||||
|
||||
customElement('md-table', { roll: false, remix: false }, (props, { element }) => {
|
||||
noShadowDOM();
|
||||
const [rows, setRows] = createSignal<TableRow[]>([]);
|
||||
|
|
@ -41,26 +38,6 @@ customElement('md-table', { roll: false, remix: false }, (props, { element }) =>
|
|||
// 解析相对路径
|
||||
const resolvedSrc = resolvePath(articlePath, src);
|
||||
|
||||
// 加载 CSV 文件的函数
|
||||
const loadCSV = async (path: string): Promise<TableRow[]> => {
|
||||
// 先从缓存获取
|
||||
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 TableRow[];
|
||||
// 缓存结果
|
||||
csvCache.set(path, result);
|
||||
return result;
|
||||
};
|
||||
|
||||
// 使用 createResource 加载 CSV,自动响应路径变化并避免重复加载
|
||||
const [csvData] = createResource(() => resolvedSrc, loadCSV);
|
||||
|
||||
|
|
|
|||
|
|
@ -1,17 +1,17 @@
|
|||
import { parse } from 'csv-parse/browser/esm/sync';
|
||||
import type { CardData } from '../types';
|
||||
|
||||
/**
|
||||
* 全局缓存已加载的 CSV 内容
|
||||
*/
|
||||
const csvCache = new Map<string, CardData[]>();
|
||||
const csvCache = new Map<string, Record<string, string>[]>();
|
||||
|
||||
/**
|
||||
* 加载 CSV 文件
|
||||
* @template T 返回数据的类型,默认为 Record<string, string>
|
||||
*/
|
||||
export async function loadCSV(path: string): Promise<CardData[]> {
|
||||
export async function loadCSV<T = Record<string, string>>(path: string): Promise<T[]> {
|
||||
if (csvCache.has(path)) {
|
||||
return csvCache.get(path)!;
|
||||
return csvCache.get(path)! as T[];
|
||||
}
|
||||
|
||||
const response = await fetch(path);
|
||||
|
|
@ -23,7 +23,7 @@ export async function loadCSV(path: string): Promise<CardData[]> {
|
|||
skipEmptyLines: true
|
||||
});
|
||||
|
||||
const result = records as CardData[];
|
||||
const result = records as Record<string, string>[];
|
||||
csvCache.set(path, result);
|
||||
return result;
|
||||
return result as T[];
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue