Skip to content

Commit 0394b4c

Browse files
committed
Refactor configuration handle
1 parent 6a77270 commit 0394b4c

File tree

1 file changed

+24
-11
lines changed

1 file changed

+24
-11
lines changed

src/index.ts

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,18 @@ import useSWR, { type SWRConfiguration } from "swr";
1212
import useSWRInfinite, { SWRInfiniteKeyLoader } from "swr/infinite";
1313
import type { PartialDeep } from "type-fest";
1414

15-
let matchKeyComparator: ((a: object, b: object) => boolean) | undefined;
15+
export type SwrOpenApiConfiguration = {
16+
matchKeyComparator?: (a: object, b: object) => boolean;
17+
};
18+
19+
const configuration: SwrOpenApiConfiguration = {};
20+
21+
/**
22+
* Apply an optional configuration to the library at runtime
23+
*/
24+
export function applySwrOpenApiConfiguration(config: SwrOpenApiConfiguration) {
25+
Object.assign(configuration, config);
26+
}
1627

1728
export function createHooks<Paths extends {}>(
1829
api: ReturnType<typeof createClient<Paths>>,
@@ -98,6 +109,12 @@ export function createHooks<Paths extends {}>(
98109
Options extends FetchOptions<Req>,
99110
>(path: Path, pathOptions?: PartialDeep<Options>) {
100111
return (key: unknown): boolean => {
112+
if (!configuration.matchKeyComparator) {
113+
throw new Error(
114+
"Define a `matchKeyComparator` by calling `applySwrOpenApiConfiguration` in order to use `matchKey`",
115+
);
116+
}
117+
101118
if (Array.isArray(key)) {
102119
const [prefix, keyPath, keyOptions] = key;
103120
return (
@@ -106,33 +123,29 @@ export function createHooks<Paths extends {}>(
106123
// Matching path
107124
keyPath === path &&
108125
// Matching options
109-
(pathOptions ? matchKeyComparator!(keyOptions, pathOptions) : true)
126+
(pathOptions
127+
? configuration.matchKeyComparator(keyOptions, pathOptions)
128+
: true)
110129
);
111130
}
112131

113132
return false;
114133
};
115134
}
116135

117-
const localMatchKeyComparator = matchKeyComparator;
136+
const localConfig = configuration;
118137

119138
return {
120139
use,
121140
useInfinite,
122141
get matchKey() {
123-
if (!localMatchKeyComparator) {
142+
if (!localConfig.matchKeyComparator) {
124143
throw new Error(
125-
"Match key comparison is not enabled. Please call enableMatchKeyComparison with a comparator function.",
144+
"Define a `matchKeyComparator` by calling `applySwrOpenApiConfiguration` in order to use `matchKey`",
126145
);
127146
}
128147

129148
return matchKey;
130149
},
131150
};
132151
}
133-
134-
export function enableMatchKeyComparison(
135-
comparator: typeof matchKeyComparator,
136-
) {
137-
matchKeyComparator = comparator;
138-
}

0 commit comments

Comments
 (0)