Wiring WunderGraph to non-react project (generic TS)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createClient, Operations } from '<package>/.wundergraph/generated/client' | |
import { createHooks } from './hooks' | |
const client = createClient() | |
const hooks = createHooks<Operations>(client) | |
export async function foo(): Promise<void> { | |
const response = await hooks.query({ | |
operationName: '<operation>', | |
}) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Client, OperationRequestOptions, OperationsDefinition } from '@wundergraph/sdk/client' | |
export type UseQueryOptions<OperationName, Input, LiveQuery> = { | |
operationName: OperationName; | |
liveQuery?: LiveQuery; | |
enabled?: boolean; | |
input?: Input; | |
} | |
export const createHooks = <Operations extends OperationsDefinition>(client: Client) => { | |
const queryFetcher = async < | |
OperationName extends Extract<keyof Operations['queries'], string>, | |
Data extends Operations['queries'][OperationName]['data'] = Operations['queries'][OperationName]['data'], | |
RequestOptions extends OperationRequestOptions< | |
Extract<keyof Operations['queries'], string>, | |
Operations['queries'][OperationName]['input'] | |
> = OperationRequestOptions< | |
Extract<keyof Operations['queries'], string>, | |
Operations['queries'][OperationName]['input'] | |
> | |
>( | |
query: RequestOptions, | |
) => { | |
const result = await client.query<RequestOptions, Data>(query) | |
if (result.error) { | |
throw result.error | |
} | |
return result.data | |
} | |
const query = < | |
OperationName extends Extract<keyof Operations['queries'], string>, | |
Input extends Operations['queries'][OperationName]['input'] = Operations['queries'][OperationName]['input'], | |
Data extends Operations['queries'][OperationName]['data'] = Operations['queries'][OperationName]['data'], | |
LiveQuery extends Operations['queries'][OperationName]['liveQuery'] = Operations['queries'][OperationName]['liveQuery'] | |
>(options: UseQueryOptions<OperationName, Input, LiveQuery>) => { | |
return queryFetcher<OperationName, Data | undefined>(options) | |
} | |
return { | |
query | |
} | |
} |
Ah yes, my bad - missed it at the bottom of the file I was copying from!
Fixed :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks so much for this! One thing, got a missing return statement at the end. Should be: