Getting started with Genql

Genql translate JavaScript code into GraphQL queries, enabling you to get auto completion and validation for your GraphQL queries.

Generate with the cli

First install the required package from npm
bash
npm i -g @genql/cli
Then run the genql command to generate the client inside a directory.
bash
genql --schema ./schema.graphql --output ./generated # or using a graphql api url genql --endpoint https://countries.trevorblades.com --output ./generated -H 'Authorization: Bearer myToken'

Using the client

The generated files expose a functionย createClient, this creates a client you can use to send requests
typescript
import { createClient } from "./generated"; const client = createClient({ url: "https://countries.trevorblades.com", headers: { "Some-Header": "hello", }, }); client .query({ countries: { __args: { state: "USA", }, name: true, code: true, }, }) .then(console.log);

Node.js 16 and lower

Genql relies on a global fetch function, Node.js 16 doesnโ€™t have a global fetch so you will need to pass down one
javascript
import { fetch } from "undici"; // or node-fetch import { createClient } from "./generated"; const client = createClient({ url: "https://countries.trevorblades.com", fetch, });

Passing arguments

You can pass down arguments with __args.
javascript
client.query({ countries: { __args: { state: "USA", }, }, });

Fetch all scalar fields

You can use __args to fetch all scalar fields of a type.
javascript
client.query({ countries: { __scalar: true, objectType: { // you will need to manually query non scalar fields (object types) __scalar: true, }, }, });

Naming a query

You can give a name to a query with the __name field:
javascript
client.query({ __name: "GetCountries", countries: { state: true, continent: true, }, });
The generated GraphQL query will be:
graphql
query GetCountries { countries { state continent } }

Unsupported features

Currently the following GraphQL features are not supported
  • Renaming a field
  • Passing a directive
Directives could be implemented using a field like __directive, upvote this issue if you want support for directives.

Read more

๐Ÿ“ฎUsage๐ŸŒช๏ธCli reference๐ŸŽŽProgrammatic usage (library)Comparisons

Powered by Notaku