summaryrefslogtreecommitdiff
path: root/src/misc/createResource.ts
blob: 9ff57e58771d07af5701faf41ceaea343d685d8d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// from https://gist.github.com/ryanflorence/e10cc9dbc0e259759ec942ba82e5b57c
export function createResource(getPromise: (key: string) => Promise<any>) {
  let cache = {};
  const inflight = {};
  const errors = {};

  function load(key = 'default') {
    inflight[key] = getPromise(key)
      .then((val) => {
        delete inflight[key];
        cache[key] = val;
      })
      .catch((error) => {
        errors[key] = error;
      });
    return inflight[key];
  }

  function preload(key = 'default') {
    if (cache[key] !== undefined || inflight[key]) return;
    load(key);
  }

  function read(key = 'default') {
    if (cache[key] !== undefined) {
      return cache[key];
    } else if (errors[key]) {
      throw errors[key];
    } else if (inflight[key]) {
      throw inflight[key];
    } else {
      throw load(key);
    }
  }

  function clear(key: 'default') {
    if (key) {
      delete cache[key];
    } else {
      cache = {};
    }
  }

  return { preload, read, clear };
}