mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-03-26 11:21:16 +01:00
Better GraphQL schema fetching
This commit is contained in:
13
src-web/hooks/useDebouncedValue.ts
Normal file
13
src-web/hooks/useDebouncedValue.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
|
||||
export function useDebouncedValue<T extends string | number>(value: T, delay = 1000) {
|
||||
const [state, setState] = useState<T>(value);
|
||||
const timeout = useRef<NodeJS.Timeout>();
|
||||
|
||||
useEffect(() => {
|
||||
clearTimeout(timeout.current ?? 0);
|
||||
timeout.current = setTimeout(() => setState(value), delay);
|
||||
}, [value, delay]);
|
||||
|
||||
return state;
|
||||
}
|
||||
34
src-web/hooks/useIntrospectGraphQL.ts
Normal file
34
src-web/hooks/useIntrospectGraphQL.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import type { GraphQLSchema } from 'graphql';
|
||||
import { buildClientSchema, getIntrospectionQuery } from '../components/core/Editor';
|
||||
import type { HttpRequest } from '../lib/models';
|
||||
import { sendEphemeralRequest } from '../lib/sendEphemeralRequest';
|
||||
import { useDebouncedValue } from './useDebouncedValue';
|
||||
|
||||
const introspectionRequestBody = JSON.stringify({
|
||||
query: getIntrospectionQuery(),
|
||||
operationName: 'IntrospectionQuery',
|
||||
});
|
||||
|
||||
export function useIntrospectGraphQL(baseRequest: HttpRequest) {
|
||||
const url = useDebouncedValue(baseRequest.url);
|
||||
return useQuery<GraphQLSchema, Error>({
|
||||
queryKey: ['introspectGraphQL', { url }],
|
||||
refetchOnWindowFocus: true,
|
||||
// staleTime: 1000 * 60 * 60, // 1 hour
|
||||
refetchInterval: 1000 * 60, // Refetch every minute
|
||||
queryFn: async () => {
|
||||
const response = await sendEphemeralRequest({
|
||||
...baseRequest,
|
||||
body: introspectionRequestBody,
|
||||
});
|
||||
|
||||
if (response.error) {
|
||||
return Promise.reject(new Error(response.error));
|
||||
}
|
||||
|
||||
const { data } = JSON.parse(response.body);
|
||||
return buildClientSchema(data);
|
||||
},
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user