Skip to content

Commit

Permalink
add delay to snap query
Browse files Browse the repository at this point in the history
  • Loading branch information
alijany committed Jun 23, 2024
1 parent 00ecf9b commit 671fe02
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 33 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"version": "0.7.2",
"version": "0.7.3",
"license": "MIT",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
Expand Down
75 changes: 43 additions & 32 deletions src/lazyQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import {
} from "./model";
import { replaceUrlParam, wrapPromise } from "./utils";


export type LazyResponse<Res> = {
read(): {
isError: false,
Expand All @@ -23,6 +22,10 @@ export type LazyResponse<Res> = {
} | undefined
}

function delay(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}

export function createLazyHook<
DefReq = unknown,
DefRes = unknown,
Expand All @@ -44,11 +47,11 @@ export function createLazyHook<
>(
options: UseQueryParams<DefReq, ExtractRouteParams<U>> & {
validator?: ZodType<Res, ZodTypeDef>;
delay?: number; // Add delay option
}
) {
type ResType = Res extends object ? Res : DefRes


const fetchPromise = useMemo(() => {
if (options.skip) {
return {
Expand All @@ -57,39 +60,47 @@ export function createLazyHook<
},
}
}

const compiledUrl = replaceUrlParam(url, options.pathParams ?? {});

return wrapPromise(axiosInstance<ResType>({
...defaultOptions,
...options,
url: compiledUrl,
})
.then((result) => {
const validatorResult = (
options.validator
? options.validator.parse(result.data)
: defaultValidator
? defaultValidator.parse(result.data)
: result.data
) as ResType;
return {
isError: false,
isSuccess: true,
error: null,
data: validatorResult
}
const fetchData = async () => {
if (options.delay) {
await delay(options.delay);
}

return axiosInstance<ResType>({
...defaultOptions,
...options,
url: compiledUrl,
})
.catch((error) => {
if (logLevel === 'debug')
console.warn('snap-query', JSON.stringify({ error }, undefined, 2));
return {
isError: true,
isSuccess: false,
error,
data: null
}
})) as (LazyResponse<ResType>);
.then((result) => {
const validatorResult = (
options.validator
? options.validator.parse(result.data)
: defaultValidator
? defaultValidator.parse(result.data)
: result.data
) as ResType;
return {
isError: false,
isSuccess: true,
error: null,
data: validatorResult
}
})
.catch((error) => {
if (logLevel === 'debug')
console.warn('snap-query', JSON.stringify({ error }, undefined, 2));
return {
isError: true,
isSuccess: false,
error,
data: null
}
});
};

return wrapPromise(fetchData()) as LazyResponse<ResType>;
}, [options]);

return fetchPromise;
Expand Down

0 comments on commit 671fe02

Please sign in to comment.