Better GraphQL schema fetching

This commit is contained in:
Gregory Schier
2023-04-01 17:53:36 -07:00
parent 9cbe24e740
commit 11a89f06c1
6 changed files with 101 additions and 50 deletions

View File

@@ -631,8 +631,8 @@ fn create_window(handle: &AppHandle<Wry>) -> Window<Wry> {
.inner_size(1100.0, 600.0) .inner_size(1100.0, 600.0)
.hidden_title(true) .hidden_title(true)
.title(match is_dev() { .title(match is_dev() {
true => "Yaak", true => "Yaak Dev",
false => "Yaak Dev", false => "Yaak",
}) })
.title_bar_style(TitleBarStyle::Overlay) .title_bar_style(TitleBarStyle::Overlay)
.build() .build()

View File

@@ -11,8 +11,10 @@ import { DialogProvider } from './DialogContext';
import { TauriListeners } from './TauriListeners'; import { TauriListeners } from './TauriListeners';
const queryClient = new QueryClient({ const queryClient = new QueryClient({
logger: undefined,
defaultOptions: { defaultOptions: {
queries: { queries: {
retry: false,
cacheTime: 1000 * 60 * 60 * 24, // 24 hours cacheTime: 1000 * 60 * 60 * 24, // 24 hours
networkMode: 'offlineFirst', networkMode: 'offlineFirst',

View File

@@ -1,11 +1,13 @@
import { updateSchema } from 'cm6-graphql'; import { updateSchema } from 'cm6-graphql';
import type { EditorView } from 'codemirror'; import type { EditorView } from 'codemirror';
import { useCallback, useEffect, useMemo, useRef } from 'react'; import { useCallback, useEffect, useMemo, useRef } from 'react';
import { useIntrospectGraphQL } from '../hooks/useIntrospectGraphQL';
import type { HttpRequest } from '../lib/models'; import type { HttpRequest } from '../lib/models';
import { sendEphemeralRequest } from '../lib/sendEphemeralRequest'; import { Button } from './core/Button';
import type { EditorProps } from './core/Editor'; import type { EditorProps } from './core/Editor';
import { buildClientSchema, Editor, formatGraphQL, getIntrospectionQuery } from './core/Editor'; import { Editor, formatGraphQL } from './core/Editor';
import { Separator } from './core/Separator'; import { Separator } from './core/Separator';
import { useDialog } from './DialogContext';
type Props = Pick< type Props = Pick<
EditorProps, EditorProps,
@@ -21,6 +23,9 @@ interface GraphQLBody {
} }
export function GraphQLEditor({ defaultValue, onChange, baseRequest, ...extraEditorProps }: Props) { export function GraphQLEditor({ defaultValue, onChange, baseRequest, ...extraEditorProps }: Props) {
const editorViewRef = useRef<EditorView>(null);
const introspection = useIntrospectGraphQL(baseRequest);
const { query, variables } = useMemo<GraphQLBody>(() => { const { query, variables } = useMemo<GraphQLBody>(() => {
if (defaultValue === undefined) { if (defaultValue === undefined) {
return { query: '', variables: {} }; return { query: '', variables: {} };
@@ -57,39 +62,13 @@ export function GraphQLEditor({ defaultValue, onChange, baseRequest, ...extraEdi
[handleChange, query], [handleChange, query],
); );
const editorViewRef = useRef<EditorView>(null);
// Refetch the schema when the URL changes // Refetch the schema when the URL changes
useEffect(() => { useEffect(() => {
// First, clear the schema if (editorViewRef.current === null) return;
if (editorViewRef.current) { updateSchema(editorViewRef.current, introspection.data);
updateSchema(editorViewRef.current, undefined); }, [introspection.data]);
}
let unmounted = false; const dialog = useDialog();
const body = JSON.stringify({
query: getIntrospectionQuery(),
operationName: 'IntrospectionQuery',
});
sendEphemeralRequest({ ...baseRequest, body }).then((response) => {
if (unmounted) return;
if (!editorViewRef.current) return;
try {
const { data } = JSON.parse(response.body);
const schema = buildClientSchema(data);
console.log('SET SCHEMA', schema, baseRequest.url);
updateSchema(editorViewRef.current, schema);
} catch (err) {
console.log('Failed to parse introspection query', err);
}
});
return () => {
unmounted = true;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [baseRequest.url]);
return ( return (
<div className="pb-2 h-full grid grid-rows-[minmax(0,100%)_auto_auto_minmax(0,auto)]"> <div className="pb-2 h-full grid grid-rows-[minmax(0,100%)_auto_auto_minmax(0,auto)]">
@@ -101,6 +80,23 @@ export function GraphQLEditor({ defaultValue, onChange, baseRequest, ...extraEdi
onChange={handleChangeQuery} onChange={handleChangeQuery}
placeholder="..." placeholder="..."
ref={editorViewRef} ref={editorViewRef}
actions={
introspection.error && (
<Button
size="xs"
color="danger"
onClick={() => {
dialog.show({
title: 'Introspection Failed',
size: 'sm',
render: () => <div>{introspection.error?.message}</div>,
});
}}
>
Introspection Failed
</Button>
)
}
{...extraEditorProps} {...extraEditorProps}
/> />
<Separator variant="primary" /> <Separator variant="primary" />

View File

@@ -4,9 +4,10 @@ import type { ViewUpdate } from '@codemirror/view';
import { keymap, placeholder as placeholderExt, tooltips } from '@codemirror/view'; import { keymap, placeholder as placeholderExt, tooltips } from '@codemirror/view';
import classnames from 'classnames'; import classnames from 'classnames';
import { EditorView } from 'codemirror'; import { EditorView } from 'codemirror';
import type { MutableRefObject } from 'react'; import type { MutableRefObject, ReactNode } from 'react';
import { forwardRef, memo, useCallback, useEffect, useImperativeHandle, useRef } from 'react'; import { forwardRef, memo, useCallback, useEffect, useImperativeHandle, useRef } from 'react';
import { IconButton } from '../IconButton'; import { IconButton } from '../IconButton';
import { HStack } from '../Stacks';
import './Editor.css'; import './Editor.css';
import { baseExtensions, getLanguageExtension, multiLineExtensions } from './extensions'; import { baseExtensions, getLanguageExtension, multiLineExtensions } from './extensions';
import type { GenericCompletionConfig } from './genericCompletion'; import type { GenericCompletionConfig } from './genericCompletion';
@@ -35,6 +36,7 @@ export interface EditorProps {
singleLine?: boolean; singleLine?: boolean;
format?: (v: string) => string; format?: (v: string) => string;
autocomplete?: GenericCompletionConfig; autocomplete?: GenericCompletionConfig;
actions?: ReactNode;
} }
const _Editor = forwardRef<EditorView | undefined, EditorProps>(function Editor( const _Editor = forwardRef<EditorView | undefined, EditorProps>(function Editor(
@@ -54,6 +56,7 @@ const _Editor = forwardRef<EditorView | undefined, EditorProps>(function Editor(
singleLine, singleLine,
format, format,
autocomplete, autocomplete,
actions,
}: EditorProps, }: EditorProps,
ref, ref,
) { ) {
@@ -161,21 +164,24 @@ const _Editor = forwardRef<EditorView | undefined, EditorProps>(function Editor(
<div className="group relative h-full w-full"> <div className="group relative h-full w-full">
{cmContainer} {cmContainer}
{format && ( {format && (
<IconButton <HStack space={0.5} alignItems="center" className="absolute bottom-2 right-0 ">
showConfirm {actions}
size="sm" <IconButton
title="Reformat contents" showConfirm
icon="magicWand" size="sm"
className="absolute bottom-2 right-0 transition-opacity opacity-0 group-hover:opacity-70" title="Reformat contents"
onClick={() => { icon="magicWand"
if (cm.current === null) return; className="transition-opacity opacity-0 group-hover:opacity-70"
const { doc } = cm.current.view.state; onClick={() => {
const insert = format(doc.toString()); if (cm.current === null) return;
// Update editor and blur because the cursor will reset anyway const { doc } = cm.current.view.state;
cm.current.view.dispatch({ changes: { from: 0, to: doc.length, insert } }); const insert = format(doc.toString());
cm.current.view.contentDOM.blur(); // Update editor and blur because the cursor will reset anyway
}} cm.current.view.dispatch({ changes: { from: 0, to: doc.length, insert } });
/> cm.current.view.contentDOM.blur();
}}
/>
</HStack>
)} )}
</div> </div>
); );

View 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;
}

View 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);
},
});
}