Skip to main content

Codegen

Given it's configuration, creates a typed gqless client from a graphql endpoint/schema.

Installation#

Install the following dependencies to your project:

npm install gqless
npm install -D @gqless/cli graphql

Command#

After @gless/cli is installed in your package, you should add a script in your package.json.

{
"scripts": {
"generate": "gqless generate"
}
}

Then, you can execute:

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 '@gqless/react';
import { createSubscriptionsClient } from '@gqless/subscriptions';
import { createClient, QueryFetcher } from 'gqless';
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,
} = 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.

Last updated on by Sam Denty