summaryrefslogtreecommitdiff
path: root/src/misc/createResource.ts
diff options
context:
space:
mode:
authorHaishan <[email protected]>2020-10-11 19:31:32 +0800
committerHaishan <[email protected]>2020-10-12 20:42:41 +0800
commit9b52b331806a9183ee7e5b89d98c610b2a241e64 (patch)
treef9587bf35301c13494893fcc35da415dc3013d96 /src/misc/createResource.ts
parent2ad0217ee4d9c32dcd0a97043efe989155751dd4 (diff)
build: upgrade to webpack 5
Diffstat (limited to 'src/misc/createResource.ts')
-rw-r--r--src/misc/createResource.ts45
1 files changed, 45 insertions, 0 deletions
diff --git a/src/misc/createResource.ts b/src/misc/createResource.ts
new file mode 100644
index 0000000..9ff57e5
--- /dev/null
+++ b/src/misc/createResource.ts
@@ -0,0 +1,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 };
+}