threepipe
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

cache.ts 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import {Cache as threeCache} from 'three'
  2. export function overrideThreeCache(storage: Cache | Storage) {
  3. const oldCache = {...threeCache}
  4. threeCache.get = (url: string, responseType?: string, mimeType?: DOMParserSupportedType): Promise<any> | any => {
  5. if (!responseType) return oldCache.get(url)
  6. if (url.startsWith('data:') || url.startsWith('blob') || url.startsWith('chrome-extension')) return Promise.resolve(undefined)
  7. return (storage as Cache).match(url).then(response => {
  8. if (!response) return undefined
  9. switch (responseType) {
  10. case 'arraybuffer':
  11. return response.arrayBuffer()
  12. case 'blob':
  13. return response.blob()
  14. case 'document':
  15. return response.text()
  16. .then(text => {
  17. const parser = new DOMParser()
  18. return parser.parseFromString(text, mimeType ?? 'text/html')
  19. })
  20. case 'json':
  21. return response.json()
  22. default:
  23. if (mimeType === undefined) {
  24. return response.text()
  25. } else {
  26. // sniff encoding
  27. const re = /charset="?([^;"\s]*)"?/i
  28. const exec = re.exec(mimeType)
  29. const label = exec && exec[1] ? exec[1].toLowerCase() : undefined
  30. const decoder = new TextDecoder(label)
  31. return response.arrayBuffer().then(ab => decoder.decode(ab))
  32. }
  33. }
  34. })
  35. }
  36. threeCache.add = async(url: string, data: BodyInit, responseType?: string) => {
  37. if (!responseType) return oldCache.add(url, data)
  38. if (url.startsWith('data:') || url.startsWith('blob') || url.startsWith('chrome-extension')) return
  39. // noinspection JSIgnoredPromiseFromCall
  40. if (await storage.match(url)) await storage.delete(url)
  41. await storage.put(url, new Response(data, {status: 200}))
  42. }
  43. threeCache.remove = (url: string, responseType?: string) => {
  44. if (!responseType) return oldCache.remove(url)
  45. // noinspection JSIgnoredPromiseFromCall
  46. storage.delete(url)
  47. }
  48. }