| 5 | type Parameter<G> = G extends (arg: infer G) => any ? G : never; |
| 6 | |
| 7 | export function createRequest<F extends (arg: any) => Promise<any>>( |
| 8 | parameter: Ref<Parameter<F>>, |
| 9 | fn: F, |
| 10 | options: { |
| 11 | cache?: { |
| 12 | prefix: string; |
| 13 | ttl: number; |
| 14 | refetchTtl: number; |
| 15 | keyFn?: (param: Ref<Parameter<F>>) => string; |
| 16 | }; |
| 17 | executeCondition?: (param: Ref<Parameter<F>>) => boolean; |
| 18 | keepData?: boolean; |
| 19 | } = {}, |
| 20 | ) { |
| 21 | let id = 0; |
| 22 | |
| 23 | const result = reactive({ |
| 24 | loading: true, |
| 25 | temporaryCache: false, |
| 26 | cache: false, |
| 27 | data: null as null | Awaited<ReturnType<F>>, |
| 28 | error: null as null | Error, |
| 29 | execute: () => Promise.resolve(), |
| 30 | }); |
| 31 | |
| 32 | const execute = async (params: Ref<Parameter<F>>, forceFresh = false) => { |
| 33 | result.loading = true; |
| 34 | result.temporaryCache = false; |
| 35 | result.error = null; |
| 36 | if (!options.keepData) result.data = null; |
| 37 | const tempId = Math.random(); |
| 38 | id = tempId; |
| 39 | |
| 40 | let state; |
| 41 | let cache; |
| 42 | if (options.cache) { |
| 43 | cache = new Cache( |
| 44 | options.cache.prefix + |
| 45 | (options.cache.keyFn ? options.cache.keyFn(params) : JSON.stringify(params.value)), |
| 46 | options.cache.ttl, |
| 47 | true, |
| 48 | options.cache.refetchTtl, |
| 49 | ); |
| 50 | |
| 51 | if (forceFresh) { |
| 52 | cache.clearValue(); |
| 53 | } else { |
| 54 | state = await cache.fullState(); |
| 55 | if (state.hasValue) { |
| 56 | result.data = state.value.data; |
| 57 | result.loading = false; |
| 58 | result.cache = true; |
| 59 | result.temporaryCache = state.refetch; |
| 60 | } |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | if (state && !state.refetch && state.hasValue) return Promise.resolve(); |