Guest User

Untitled

a guest
Nov 17th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. export interface CachedResource<I extends any[], V> {
  2. load(...input: I): Promise<V>
  3. loadSuspended(...input: I): V
  4. has(...input: I): boolean
  5. get(...input: I): V | undefined
  6. set(item: V, ...input: I): void
  7. invalidate(...input: I): void
  8. clear(): void
  9. }
  10.  
  11. export default function createCachedResource<I extends any[], V>(
  12. loadResource: (...input: I) => Promise<V>,
  13. hashInput?: (...input: I) => string,
  14. ): CachedResource<I, V> {
  15. const cache = new Map<string, V>()
  16. const errors = new Map<string, any>()
  17.  
  18. const getKeyFromInput = (...input: I) =>
  19. hashInput ? hashInput(...input) : input.join("-")
  20.  
  21. async function load(...input: I) {
  22. const key = getKeyFromInput(...input)
  23.  
  24. try {
  25. errors.delete(key)
  26.  
  27. const data = cache.get(key) || (await loadResource(...input))
  28. cache.set(key, data)
  29. return data
  30. } catch (error) {
  31. errors.set(key, error)
  32. throw error
  33. }
  34. }
  35.  
  36. return {
  37. load,
  38.  
  39. loadSuspended(...input: I) {
  40. const key = getKeyFromInput(...input)
  41.  
  42. const data = cache.get(key)
  43. if (data) return data
  44.  
  45. const error = errors.get(key)
  46. if (error) throw error
  47.  
  48. throw load(...input) // 👀
  49. },
  50.  
  51. has(...input: I) {
  52. return cache.has(getKeyFromInput(...input))
  53. },
  54.  
  55. get(...input: I) {
  56. return cache.get(getKeyFromInput(...input))
  57. },
  58.  
  59. set(item: V, ...input: I) {
  60. cache.set(getKeyFromInput(...input), item)
  61. },
  62.  
  63. invalidate(...input: I) {
  64. cache.delete(getKeyFromInput(...input))
  65. },
  66.  
  67. clear() {
  68. cache.clear()
  69. },
  70. }
  71. }
Add Comment
Please, Sign In to add comment