@marianmeres/fetch-store 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +83 -0
- package/dist/index.cjs +1 -0
- package/dist/index.d.ts +28 -0
- package/dist/index.js +1 -0
- package/dist/index.umd.js +1 -0
- package/package.json +60 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023 Marian Meres
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# @marianmeres/fetch-store
|
|
2
|
+
|
|
3
|
+
[Store](https://github.com/marianmeres/store) utility for collecting results and meta info
|
|
4
|
+
of any type of async work. Typically used for http requests.
|
|
5
|
+
|
|
6
|
+
## Install
|
|
7
|
+
```shell
|
|
8
|
+
$ npm i @marianmeres/fetch-store
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Basic example
|
|
12
|
+
|
|
13
|
+
```javascript
|
|
14
|
+
// foo-store.js
|
|
15
|
+
const foo = createFetchStore(
|
|
16
|
+
async () => {
|
|
17
|
+
const r = await fetch('foo.json');
|
|
18
|
+
if (!r.ok) throw new Error('Not OK!');
|
|
19
|
+
return await r.json()
|
|
20
|
+
}
|
|
21
|
+
);
|
|
22
|
+
```
|
|
23
|
+
```sveltehtml
|
|
24
|
+
<!--FooComponent.svelte-->
|
|
25
|
+
<script>
|
|
26
|
+
onMount(foo.fetch)
|
|
27
|
+
</script>
|
|
28
|
+
|
|
29
|
+
{#if $foo.isFetching}
|
|
30
|
+
<Spinner />
|
|
31
|
+
{:else if $foo.lastFetchError}
|
|
32
|
+
<Error error={$foo.lastFetchError} />
|
|
33
|
+
{:else}
|
|
34
|
+
<Foo foo={$foo.data} />
|
|
35
|
+
{/if}
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Api
|
|
39
|
+
|
|
40
|
+
```typescript
|
|
41
|
+
const store = createFetchStore<T>(
|
|
42
|
+
// the async worker
|
|
43
|
+
fetchWorker: (...args) => Promise<any>,
|
|
44
|
+
// optional, initial `data` value of the store
|
|
45
|
+
initial?: T = null,
|
|
46
|
+
// optional, used to modify data returned by fetchWorker... (usefull for various
|
|
47
|
+
// data update strategies, like merge/deepmerge/set etc)
|
|
48
|
+
dataFactory?: (raw: any, old?: any) => T = null,
|
|
49
|
+
// options (see source)
|
|
50
|
+
options? = null
|
|
51
|
+
);
|
|
52
|
+
|
|
53
|
+
// subscription
|
|
54
|
+
store.subscribe((v) => {
|
|
55
|
+
// main result
|
|
56
|
+
// v.data: T;
|
|
57
|
+
|
|
58
|
+
// meta
|
|
59
|
+
// v.isFetching: boolean;
|
|
60
|
+
// v.lastFetchStart: Date;
|
|
61
|
+
// v.lastFetchEnd: Date;
|
|
62
|
+
// v.lastFetchError: Date;
|
|
63
|
+
// v.successCounter: number;
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
// instance api
|
|
67
|
+
|
|
68
|
+
// do the async work
|
|
69
|
+
store.fetch: (...args) => Promise<void>;
|
|
70
|
+
|
|
71
|
+
// do the async work, but do not update meta
|
|
72
|
+
store.fetchSilent: (...args) => Promise<void>;
|
|
73
|
+
|
|
74
|
+
// fetch only once (if within threshold since last)
|
|
75
|
+
store.fetchOnce: (args: any[], thresholdMs: number) => Promise<void>;
|
|
76
|
+
|
|
77
|
+
// to reset internal meta store
|
|
78
|
+
store.reset: Function;
|
|
79
|
+
store.resetError: Function;
|
|
80
|
+
|
|
81
|
+
// for manual hackings
|
|
82
|
+
store.getInternalDataStore();
|
|
83
|
+
```
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";const e=e=>"function"==typeof e,t=(t,r="")=>{if(!e(t))throw new TypeError(`${r} Expecting function arg`.trim())},r=t=>e(t.subscribe),s=(r=undefined,s=null)=>{const n=t=>e(s?.persist)&&s.persist(t);let c=(()=>{const e=new Map,t=t=>(e.has(t)||e.set(t,new Set),e.get(t)),r=(e,r)=>{if("function"!=typeof r)throw new TypeError("Expecting callback function as second argument");return t(e).add(r),()=>t(e).delete(r)};return{publish:(e,r={})=>{t(e).forEach((e=>e(r)))},subscribe:r,subscribeOnce:(e,t)=>{const s=r(e,(e=>{t(e),s()}));return s},unsubscribeAll:t=>e.delete(t)}})(),a=r;n(a);const l=()=>a,i=e=>{a!==e&&(a=e,n(a),c.publish("change",a))};return{set:i,get:l,update:e=>{t(e,"[update]"),i(e(l()))},subscribe:e=>(t(e,"[subscribe]"),e(a),c.subscribe("change",e))}},n={fetchSilentDefaultThresholdMs:3e5},c=e=>"function"==typeof e;exports.createFetchStore=(a,l=null,i=null,u=null)=>{const{logger:o,onError:h,onSilentError:g,afterCreate:b,fetchSilentDefaultThresholdMs:f}={...n,...u||{}},p=(e,t)=>c(i)?i(e,t):e,E=s(p(l)),d=s({isFetching:!1,lastFetchStart:null,lastFetchEnd:null,lastFetchError:null,successCounter:0}),{subscribe:w,get:F}=((n,c,a=null)=>{const l=t=>e(a?.persist)&&a.persist(t),i=s(a?.initialValue),u=[];if(n.forEach((e=>{if(!r(e))throw new TypeError("Expecting array of StoreLike objects");e.subscribe((e=>u.push(e)))()})),!e(c))throw new TypeError("Expecting second argument to be the derivative function");if(!c.length||c.length>2)throw new TypeError("Expecting the derivative function to have exactly 1 or 2 arguments");let o=0,h=[];return{get:i.get,subscribe:e=>{t(e,"[derived.subscribe]"),o++||n.forEach(((e,t)=>{h.push(e.subscribe((e=>{u[t]=e,1===c.length?(i.set(c(u)),l(i.get())):c(u,(e=>{i.set(e),l(i.get())}))})))}));const r=i.subscribe(e);return()=>{--o||(h.forEach((e=>e())),h=[]),r()}}}})([E,d],(([e,t])=>({data:e,...t})));w((()=>null));const y=async(...e)=>{let t=E.get(),r=d.get();const s=new Date;let n=null;d.set({...r,isFetching:!0,lastFetchStart:s,lastFetchEnd:null,lastFetchError:n});try{t=p(await a(...e),t),r.successCounter++}catch(e){n=e}E.set(t),d.set({...r,isFetching:!1,lastFetchStart:s,lastFetchEnd:new Date,lastFetchError:n}),n&&c(h)&&h(n)},S={subscribe:w,get:F,fetch:y,fetchSilent:async(...e)=>{try{E.set(p(await a(...e),E.get()))}catch(e){((...e)=>{c(o)&&o.apply(null,e)})("silent fetch error",e),c(g)&&g(e)}},fetchOnce:async(e=[],t=f)=>{const{successCounter:r,isFetching:s,lastFetchStart:n}=d.get();return Array.isArray(e)||(e=[e]),r||s?t&&!s&&n&&Date.now()-new Date(n).valueOf()>t?await y(...e):void 0:await y(...e)},reset:()=>{E.set(p(l)),d.set({isFetching:!1,lastFetchStart:null,lastFetchEnd:null,lastFetchError:null,successCounter:0})},resetError:()=>d.update((e=>({...e,lastFetchError:null}))),getInternalDataStore:()=>E};return c(b)&&b(S),S};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { StoreLike, StoreReadable } from '@marianmeres/store';
|
|
2
|
+
export interface FetchStoreMeta {
|
|
3
|
+
isFetching: boolean;
|
|
4
|
+
lastFetchStart: Date;
|
|
5
|
+
lastFetchEnd: Date;
|
|
6
|
+
lastFetchError: Date;
|
|
7
|
+
successCounter: number;
|
|
8
|
+
}
|
|
9
|
+
export interface FetchStoreValue<T> extends FetchStoreMeta {
|
|
10
|
+
data: T;
|
|
11
|
+
}
|
|
12
|
+
export interface FetchStore<T, V> extends StoreReadable<T> {
|
|
13
|
+
fetch: (...args: any[]) => Promise<void>;
|
|
14
|
+
fetchSilent: (...args: any[]) => Promise<void>;
|
|
15
|
+
fetchOnce: (args: any[], thresholdMs: number) => Promise<void>;
|
|
16
|
+
reset: Function;
|
|
17
|
+
resetError: Function;
|
|
18
|
+
getInternalDataStore: () => StoreLike<V>;
|
|
19
|
+
}
|
|
20
|
+
interface FetchStoreOptions {
|
|
21
|
+
logger: (...args: any[]) => void;
|
|
22
|
+
afterCreate: (fetchStoreInstance: any) => void;
|
|
23
|
+
fetchSilentDefaultThresholdMs: number;
|
|
24
|
+
onError: (e: any) => void;
|
|
25
|
+
onSilentError: (e: any) => void;
|
|
26
|
+
}
|
|
27
|
+
export declare const createFetchStore: <T>(fetchWorker: (...args: any[]) => Promise<any>, initial?: T, dataFactory?: (raw: any, old?: any) => T, options?: Partial<FetchStoreOptions>) => FetchStore<FetchStoreValue<T>, T>;
|
|
28
|
+
export {};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=e=>"function"==typeof e,t=(t,r="")=>{if(!e(t))throw new TypeError(`${r} Expecting function arg`.trim())},r=t=>e(t.subscribe),s=(r=undefined,s=null)=>{const n=t=>e(s?.persist)&&s.persist(t);let c=(()=>{const e=new Map,t=t=>(e.has(t)||e.set(t,new Set),e.get(t)),r=(e,r)=>{if("function"!=typeof r)throw new TypeError("Expecting callback function as second argument");return t(e).add(r),()=>t(e).delete(r)};return{publish:(e,r={})=>{t(e).forEach((e=>e(r)))},subscribe:r,subscribeOnce:(e,t)=>{const s=r(e,(e=>{t(e),s()}));return s},unsubscribeAll:t=>e.delete(t)}})(),l=r;n(l);const a=()=>l,i=e=>{l!==e&&(l=e,n(l),c.publish("change",l))};return{set:i,get:a,update:e=>{t(e,"[update]"),i(e(a()))},subscribe:e=>(t(e,"[subscribe]"),e(l),c.subscribe("change",e))}},n={fetchSilentDefaultThresholdMs:3e5},c=e=>"function"==typeof e,l=(l,a=null,i=null,u=null)=>{const{logger:o,onError:h,onSilentError:g,afterCreate:b,fetchSilentDefaultThresholdMs:f}={...n,...u||{}},p=(e,t)=>c(i)?i(e,t):e,E=s(p(a)),d=s({isFetching:!1,lastFetchStart:null,lastFetchEnd:null,lastFetchError:null,successCounter:0}),{subscribe:w,get:F}=((n,c,l=null)=>{const a=t=>e(l?.persist)&&l.persist(t),i=s(l?.initialValue),u=[];if(n.forEach((e=>{if(!r(e))throw new TypeError("Expecting array of StoreLike objects");e.subscribe((e=>u.push(e)))()})),!e(c))throw new TypeError("Expecting second argument to be the derivative function");if(!c.length||c.length>2)throw new TypeError("Expecting the derivative function to have exactly 1 or 2 arguments");let o=0,h=[];return{get:i.get,subscribe:e=>{t(e,"[derived.subscribe]"),o++||n.forEach(((e,t)=>{h.push(e.subscribe((e=>{u[t]=e,1===c.length?(i.set(c(u)),a(i.get())):c(u,(e=>{i.set(e),a(i.get())}))})))}));const r=i.subscribe(e);return()=>{--o||(h.forEach((e=>e())),h=[]),r()}}}})([E,d],(([e,t])=>({data:e,...t})));w((()=>null));const y=async(...e)=>{let t=E.get(),r=d.get();const s=new Date;let n=null;d.set({...r,isFetching:!0,lastFetchStart:s,lastFetchEnd:null,lastFetchError:n});try{t=p(await l(...e),t),r.successCounter++}catch(e){n=e}E.set(t),d.set({...r,isFetching:!1,lastFetchStart:s,lastFetchEnd:new Date,lastFetchError:n}),n&&c(h)&&h(n)},S={subscribe:w,get:F,fetch:y,fetchSilent:async(...e)=>{try{E.set(p(await l(...e),E.get()))}catch(e){((...e)=>{c(o)&&o.apply(null,e)})("silent fetch error",e),c(g)&&g(e)}},fetchOnce:async(e=[],t=f)=>{const{successCounter:r,isFetching:s,lastFetchStart:n}=d.get();return Array.isArray(e)||(e=[e]),r||s?t&&!s&&n&&Date.now()-new Date(n).valueOf()>t?await y(...e):void 0:await y(...e)},reset:()=>{E.set(p(a)),d.set({isFetching:!1,lastFetchStart:null,lastFetchEnd:null,lastFetchError:null,successCounter:0})},resetError:()=>d.update((e=>({...e,lastFetchError:null}))),getInternalDataStore:()=>E};return c(b)&&b(S),S};export{l as createFetchStore};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).ticker={})}(this,(function(e){"use strict";const t=e=>"function"==typeof e,r=(e,r="")=>{if(!t(e))throw new TypeError(`${r} Expecting function arg`.trim())},n=e=>t(e.subscribe),s=(e=undefined,n=null)=>{const s=e=>t(n?.persist)&&n.persist(e);let c=(()=>{const e=new Map,t=t=>(e.has(t)||e.set(t,new Set),e.get(t)),r=(e,r)=>{if("function"!=typeof r)throw new TypeError("Expecting callback function as second argument");return t(e).add(r),()=>t(e).delete(r)};return{publish:(e,r={})=>{t(e).forEach((e=>e(r)))},subscribe:r,subscribeOnce:(e,t)=>{const n=r(e,(e=>{t(e),n()}));return n},unsubscribeAll:t=>e.delete(t)}})(),l=e;s(l);const i=()=>l,a=e=>{l!==e&&(l=e,s(l),c.publish("change",l))};return{set:a,get:i,update:e=>{r(e,"[update]"),a(e(i()))},subscribe:e=>(r(e,"[subscribe]"),e(l),c.subscribe("change",e))}},c={fetchSilentDefaultThresholdMs:3e5},l=e=>"function"==typeof e;e.createFetchStore=(e,i=null,a=null,o=null)=>{const{logger:u,onError:h,onSilentError:f,afterCreate:b,fetchSilentDefaultThresholdMs:g}={...c,...o||{}},p=(e,t)=>l(a)?a(e,t):e,d=s(p(i)),E=s({isFetching:!1,lastFetchStart:null,lastFetchEnd:null,lastFetchError:null,successCounter:0}),{subscribe:y,get:w}=((e,c,l=null)=>{const i=e=>t(l?.persist)&&l.persist(e),a=s(l?.initialValue),o=[];if(e.forEach((e=>{if(!n(e))throw new TypeError("Expecting array of StoreLike objects");e.subscribe((e=>o.push(e)))()})),!t(c))throw new TypeError("Expecting second argument to be the derivative function");if(!c.length||c.length>2)throw new TypeError("Expecting the derivative function to have exactly 1 or 2 arguments");let u=0,h=[];return{get:a.get,subscribe:t=>{r(t,"[derived.subscribe]"),u++||e.forEach(((e,t)=>{h.push(e.subscribe((e=>{o[t]=e,1===c.length?(a.set(c(o)),i(a.get())):c(o,(e=>{a.set(e),i(a.get())}))})))}));const n=a.subscribe(t);return()=>{--u||(h.forEach((e=>e())),h=[]),n()}}}})([d,E],(([e,t])=>({data:e,...t})));y((()=>null));const F=async(...t)=>{let r=d.get(),n=E.get();const s=new Date;let c=null;E.set({...n,isFetching:!0,lastFetchStart:s,lastFetchEnd:null,lastFetchError:c});try{r=p(await e(...t),r),n.successCounter++}catch(e){c=e}d.set(r),E.set({...n,isFetching:!1,lastFetchStart:s,lastFetchEnd:new Date,lastFetchError:c}),c&&l(h)&&h(c)},S={subscribe:y,get:w,fetch:F,fetchSilent:async(...t)=>{try{d.set(p(await e(...t),d.get()))}catch(e){((...e)=>{l(u)&&u.apply(null,e)})("silent fetch error",e),l(f)&&f(e)}},fetchOnce:async(e=[],t=g)=>{const{successCounter:r,isFetching:n,lastFetchStart:s}=E.get();return Array.isArray(e)||(e=[e]),r||n?t&&!n&&s&&Date.now()-new Date(s).valueOf()>t?await F(...e):void 0:await F(...e)},reset:()=>{d.set(p(i)),E.set({isFetching:!1,lastFetchStart:null,lastFetchEnd:null,lastFetchError:null,successCounter:0})},resetError:()=>E.update((e=>({...e,lastFetchError:null}))),getInternalDataStore:()=>d};return l(b)&&b(S),S}}));
|
package/package.json
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@marianmeres/fetch-store",
|
|
3
|
+
"version": "1.0.2",
|
|
4
|
+
"description": "",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.cjs",
|
|
7
|
+
"module": "./dist/index.js",
|
|
8
|
+
"browser": "./dist/index.umd.js",
|
|
9
|
+
"exports": {
|
|
10
|
+
"require": "./dist/index.cjs",
|
|
11
|
+
"import": "./dist/index.js"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"dist"
|
|
15
|
+
],
|
|
16
|
+
"types": "./dist/index.d.ts",
|
|
17
|
+
"scripts": {
|
|
18
|
+
"clean": "rimraf dist/*",
|
|
19
|
+
"prettier": "prettier --write \"{src,tests}/**/*.{js,ts,json}\"",
|
|
20
|
+
"release": "release",
|
|
21
|
+
"test": "node --loader ts-node/esm tests/index.ts",
|
|
22
|
+
"test:watch": "nodemon --delay 0.5 -q -w \"src/**/*.*\" -w \"tests/**/*.*\" -x \"node --loader ts-node/esm tests/index.ts\" --",
|
|
23
|
+
"build": "npm run clean && rollup -c",
|
|
24
|
+
"dev": "npm run clean && rollup -c -w"
|
|
25
|
+
},
|
|
26
|
+
"repository": {
|
|
27
|
+
"type": "git",
|
|
28
|
+
"url": "git+https://github.com/marianmeres/fetch-store.git"
|
|
29
|
+
},
|
|
30
|
+
"keywords": [
|
|
31
|
+
"interval"
|
|
32
|
+
],
|
|
33
|
+
"author": "Marian Meres <marian@meres.sk>",
|
|
34
|
+
"license": "MIT",
|
|
35
|
+
"bugs": {
|
|
36
|
+
"url": "https://github.com/marianmeres/ticker/issues"
|
|
37
|
+
},
|
|
38
|
+
"homepage": "https://github.com/marianmeres/ticker#readme",
|
|
39
|
+
"devDependencies": {
|
|
40
|
+
"@marianmeres/clog": "^1.0.0",
|
|
41
|
+
"@marianmeres/release": "^1.0.0",
|
|
42
|
+
"@marianmeres/test-runner": "^2.0.15",
|
|
43
|
+
"@rollup/plugin-commonjs": "^24.0.1",
|
|
44
|
+
"@rollup/plugin-node-resolve": "^15.0.1",
|
|
45
|
+
"@rollup/plugin-terser": "^0.4.0",
|
|
46
|
+
"@rollup/plugin-typescript": "^11.0.0",
|
|
47
|
+
"@types/node": "^18.15.1",
|
|
48
|
+
"mkdirp": "^2.1.5",
|
|
49
|
+
"nodemon": "^2.0.21",
|
|
50
|
+
"prettier": "^2.8.4",
|
|
51
|
+
"rimraf": "^4.4.0",
|
|
52
|
+
"rollup": "^3.19.1",
|
|
53
|
+
"ts-node": "^10.9.1",
|
|
54
|
+
"tslib": "^2.5.0",
|
|
55
|
+
"typescript": "^4.9.5"
|
|
56
|
+
},
|
|
57
|
+
"dependencies": {
|
|
58
|
+
"@marianmeres/store": "^1.2.0"
|
|
59
|
+
}
|
|
60
|
+
}
|