index.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * @Author: fxs bjnsfxs@163.com
  3. * @Date: 2024-08-31 14:51:20
  4. * @LastEditors: fxs bjnsfxs@163.com
  5. * @LastEditTime: 2024-10-14 16:11:04
  6. * @FilePath: \Game-Backstage-Management-System\src\utils\resource\index.ts
  7. * @Description:
  8. *
  9. */
  10. // 缓存对象
  11. const resourceCache: Record<string, string> = {}
  12. /**
  13. * 加载资源并且缓存这个资源
  14. * 如果资源已经被加载过,则直接返回缓存中的资源
  15. *
  16. * @param url - 资源的加载路径
  17. * @returns 返回blob对象的url
  18. */
  19. export const loadResource = async (url: string): Promise<string> => {
  20. // 检查是否已经存储了这个资源,已经缓存了就直接返回
  21. if (resourceCache[url]) {
  22. return Promise.resolve(resourceCache[url])
  23. }
  24. // 如果没有缓存则去请求这个资源,并将他转为bolb对象,并且缓存blob对象的ulr
  25. try {
  26. const resourceBlob = await fetch(url)
  27. if (!resourceBlob.ok) throw new Error(`资源加载失败: ${url}`)
  28. const blob = await resourceBlob.blob()
  29. const objectURL = URL.createObjectURL(blob)
  30. resourceCache[url] = objectURL
  31. return objectURL
  32. } catch (err) {
  33. console.log(err)
  34. throw new Error('资源加载失败')
  35. }
  36. }
  37. /**
  38. * @description: 初始化加载所有的资源
  39. * @param {Record} resourceObj 请求的url对象,键值都为string,key为资源的名称,值为资源的请求地址
  40. * @return {*} 返回一个包含了key和blobURL的对象,用来表示所有资源的请求情况
  41. */
  42. export const initLoadResouce = (
  43. resourceObj: Record<string, string>
  44. ): Promise<Record<string, string>> => {
  45. // 获取所有的 URL 列表
  46. let urlList = Object.entries(resourceObj) // [key, url] 格式
  47. // 创建请求列表
  48. let reqList: Promise<[string, string | null]>[] = urlList.map(([key, url]) =>
  49. loadResource(url)
  50. .then((objectURL) => [key, objectURL] as [string, string])
  51. .catch(() => [key, null] as [string, string | null])
  52. )
  53. // 使用 Promise.all 处理所有请求
  54. return Promise.all(reqList).then((results) => {
  55. // 创建返回对象
  56. let resultObj: Record<string, string> = {}
  57. results.forEach(([key, value]) => {
  58. if (value !== null) {
  59. resultObj[key] = value // 如果成功,存入结果对象中
  60. }
  61. })
  62. return resultObj // 返回所有成功的资源
  63. })
  64. }