MCPcopy Create free account
hub / github.com/MALSync/MALSync / createRequest

Function createRequest

src/_minimal/utils/reactive.ts:7–97  ·  view source on GitHub ↗
(
  parameter: Ref<Parameter<F>>,
  fn: F,
  options: {
    cache?: {
      prefix: string;
      ttl: number;
      refetchTtl: number;
      keyFn?: (param: Ref<Parameter<F>>) => string;
    };
    executeCondition?: (param: Ref<Parameter<F>>) => boolean;
    keepData?: boolean;
  } = {},
)

Source from the content-addressed store, hash-verified

5type Parameter<G> = G extends (arg: infer G) => any ? G : never;
6
7export 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();

Callers

nothing calls this directly

Calls 1

executeFunction · 0.70

Tested by

no test coverage detected