DataFetcher.js 827 B

1234567891011121314151617181920212223242526272829303132333435
  1. // 数据读取工具类
  2. class DataFetcher {
  3. constructor(basePath) {
  4. this.basePath = basePath;
  5. }
  6. // 读取文件的异步方法
  7. async fetchData(farmId, key) {
  8. const filePath = `${this.basePath}/${farmId}/${key}.json`;
  9. return this.fetchDataFilePath(filePath)
  10. }
  11. // 读取文件的异步方法
  12. async fetchDataKey(key) {
  13. const filePath = `${this.basePath}/${key}.json`;
  14. return this.fetchDataFilePath(filePath)
  15. }
  16. async fetchDataFilePath(filePath) {
  17. try {
  18. const response = await fetch(filePath);
  19. if (!response.ok) {
  20. throw new Error(`无法读取文件: ${filePath}`);
  21. }
  22. const data = await response.json();
  23. return data;
  24. } catch (error) {
  25. console.error(error);
  26. return null;
  27. }
  28. }
  29. }
  30. // 模块化导出
  31. module.exports = DataFetcher;