eden-swr
Version:
React/NextJS SWR hooks for Elysia applications with fully typed Eden
53 lines (52 loc) • 1.46 kB
JavaScript
// src/index.ts
import useSWR from "swr";
var createCacheKey = (path, opts) => {
let result = path;
if (opts?.params) {
for (const [key, value] of Object.entries(opts.params)) {
result = result.replace(`:${key}`, String(value));
}
}
if (opts?.query) {
const queryString = new URLSearchParams(opts.query).toString();
if (queryString) {
result += `?${queryString}`;
}
}
return result;
};
function createUseEdenSWR(fetch, specialPathHandlers = {}) {
function useEdenSWR(path, options = {}, swrOptions = {}) {
let cacheKey = "";
if (swrOptions.shouldFetch === false) {
cacheKey = null;
} else {
if (typeof swrOptions.cacheKey === "function" || typeof swrOptions.cacheKey === "string") {
cacheKey = swrOptions.cacheKey;
} else {
if (swrOptions.cacheKey === void 0)
cacheKey = createCacheKey(path, options);
}
}
return useSWR(
cacheKey,
async () => {
let processedPath = path;
if (processedPath in specialPathHandlers && specialPathHandlers[processedPath]) {
processedPath = specialPathHandlers[processedPath](processedPath);
}
const response = await fetch(processedPath, options);
return response.data;
},
swrOptions
);
}
return useEdenSWR;
}
var defaultSpecialPathHandlers = {
"/index": () => ""
};
export {
createUseEdenSWR,
defaultSpecialPathHandlers
};