ttrpg-tools/src/data-loader/index.ts

73 lines
1.8 KiB
TypeScript
Raw Normal View History

2026-02-26 09:24:26 +08:00
/**
*
*/
export interface DataIndex {
[key: string]: string;
}
/**
*
* dev 使 import.meta.glob
* cli
*/
export function getDataIndex(): DataIndex {
// @ts-ignore - import.meta.glob 在构建时会被处理
if (typeof import.meta !== 'undefined' && import.meta.glob) {
// Dev 环境:使用 import.meta.glob 动态导入
// @ts-ignore
const modules = import.meta.glob('../../content/**/*', { as: 'raw', eager: false });
const index: DataIndex = {};
for (const [path, importer] of Object.entries(modules)) {
const normalizedPath = path.replace('/src/', '/');
index[normalizedPath] = normalizedPath;
}
return index;
}
// CLI 环境:返回空索引,由 CLI 注入
return {};
}
/**
* CLI 使
*/
export function setDataIndex(index: DataIndex) {
(window as any).__TTRPG_DATA_INDEX__ = index;
}
/**
*
*/
function getIndexedData(path: string): string | null {
const index = (window as any).__TTRPG_DATA_INDEX__ as DataIndex | undefined;
if (index && index[path]) {
return index[path];
}
return null;
}
/**
*
* @param path
* @returns
*/
export async function fetchData(path: string): Promise<string> {
// 首先尝试从索引获取
const indexedData = getIndexedData(path);
if (indexedData) {
return indexedData;
}
// 索引不存在时,使用 fetch 加载
try {
const response = await fetch(path);
if (!response.ok) {
throw new Error(`Failed to fetch: ${path}`);
}
return await response.text();
} catch (error) {
console.error('fetchData error:', error);
throw error;
}
}