Codegen#
Given it's configuration, creates a typed gqty client from a graphql endpoint/schema.
Installation#
Install the following dependencies to your project:
yarn add gqty graphql
yarn add -D @gqty/cli
pnpm add gqty graphql
pnpm add -D @gqty/cli
npm install gqty graphql
npm install -D @gqty/cli
Command#
After @gless/cli
is installed in your package, you should add a script
in your package.json
.
{
"scripts": {
"generate": "gqty generate"
}
}
Then, you can execute:
yarn generate
pnpm generate
npm run generate
Format output code#
The CLI code generator comes with built in support for formatting code using Prettier. The config search will start at the output directory and will continue up the directories tree.
Default client generated code#
By default with react
& subscriptions
turned on, the generated client files should look like this:
import { createReactClient } from '@gqty/react';
import { createSubscriptionsClient } from '@gqty/subscriptions';
import { createClient, QueryFetcher } from 'gqty';
import {
GeneratedSchema,
generatedSchema,
scalarsEnumsHash,
SchemaObjectTypes,
SchemaObjectTypesNames,
} from './schema.generated';
const queryFetcher: QueryFetcher = async function (query, variables) {
// Modify "/api/graphql" if needed
const response = await fetch('/api/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
query,
variables,
}),
mode: 'cors',
});
const json = await response.json();
return json;
};
const subscriptionsClient =
typeof window !== 'undefined'
? createSubscriptionsClient({
wsEndpoint: () => {
// Modify if needed
const url = new URL('/api/graphql', window.location.href);
url.protocol = url.protocol.replace('http', 'ws');
return url.href;
},
})
: undefined;
export const client = createClient<
GeneratedSchema,
SchemaObjectTypesNames,
SchemaObjectTypes
>({
schema: generatedSchema,
scalarsEnumsHash,
queryFetcher,
subscriptionsClient,
});
export const {
query,
mutation,
mutate,
subscription,
resolved,
refetch,
track,
} = client;
export const {
graphql,
useQuery,
useTransactionQuery,
useLazyQuery,
useMutation,
useRefetch,
useMetaState,
prepareReactRender,
useHydrateCache,
prepareQuery,
useSubscription,
} = createReactClient<GeneratedSchema>(client, {
defaults: {
// Set this flag as "true" if your usage involves React Suspense
// Keep in mind that you can overwrite it in a per-hook basis
suspense: false,
// Set this flag based on your needs
staleWhileRevalidate: false,
},
});
export * from './schema.generated';
You can modify this file safely, and each client has configurations you can set.