|
| 1 | +import axios from "axios"; |
| 2 | +import safeStringify from "fast-safe-stringify"; |
1 | 3 | import type { |
2 | 4 | QueryFunctionContext, |
3 | 5 | QueryKey, |
@@ -99,3 +101,64 @@ export type TypedUseSDKMutation<T extends DeepAsyncFnRecord<T>> = { |
99 | 101 | }; |
100 | 102 |
|
101 | 103 | type Awaited<T> = T extends PromiseLike<infer U> ? U : T; |
| 104 | + |
| 105 | +export function getTypedSDKInstance(p: { |
| 106 | + doFetch: DoFetch; |
| 107 | + queryClient?: QueryClient; |
| 108 | +}) { |
| 109 | + const getNextQuery = (path: string[]): any => { |
| 110 | + return new Proxy( |
| 111 | + () => {}, //use function as base, so that it can be called... |
| 112 | + { |
| 113 | + apply: (__, ___, args) => { |
| 114 | + const argument = args[0]; |
| 115 | + |
| 116 | + const prom = p.doFetch({ argument, path }); |
| 117 | + |
| 118 | + if (p.queryClient) { |
| 119 | + prom.then((resp: any) => { |
| 120 | + p.queryClient?.setQueryData(getQueryKey(path, argument), resp); |
| 121 | + }); |
| 122 | + } |
| 123 | + |
| 124 | + return prom; |
| 125 | + }, |
| 126 | + get(__, prop) { |
| 127 | + return getNextQuery(path.concat(prop.toString())); |
| 128 | + }, |
| 129 | + } |
| 130 | + ); |
| 131 | + }; |
| 132 | + |
| 133 | + return getNextQuery([]); |
| 134 | +} |
| 135 | + |
| 136 | +export function getQueryKey(path: string[], argument: unknown) { |
| 137 | + const queryKey = [...path]; |
| 138 | + if (argument !== "undefined") { |
| 139 | + queryKey.push(safeStringify.stableStringify(argument)); |
| 140 | + } |
| 141 | + return queryKey; |
| 142 | +} |
| 143 | + |
| 144 | +export function getFetchFn( |
| 145 | + opts: { userSuppliedDoFetch: DoFetch } | { defaultUrl: string } |
| 146 | +): DoFetch { |
| 147 | + return (p) => { |
| 148 | + if ("userSuppliedDoFetch" in opts) { |
| 149 | + return opts.userSuppliedDoFetch(p); |
| 150 | + } else { |
| 151 | + if (!opts.defaultUrl) { |
| 152 | + throw new Error( |
| 153 | + "url must be supplied to SDK constructor if no doFetch function is provided" |
| 154 | + ); |
| 155 | + } |
| 156 | + |
| 157 | + return axios |
| 158 | + .post(`${opts.defaultUrl}/${p.path.join("/")}`, { |
| 159 | + argument: p.argument, |
| 160 | + }) |
| 161 | + .then((resp) => resp.data); |
| 162 | + } |
| 163 | + }; |
| 164 | +} |
0 commit comments