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
bashnpm i -g @genql/cli
Then run the genql command to generate the client inside a directory.
bashgenql --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 requeststypescriptimport { 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
javascriptimport { 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
.javascriptclient.query({ countries: { __args: { state: "USA", }, }, });
Fetch all scalar fields
You can use
__args
to fetch all scalar fields of a type.javascriptclient.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:javascriptclient.query({ __name: "GetCountries", countries: { state: true, continent: true, }, });
The generated GraphQL query will be:
graphqlquery 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.