Request objects
Gqlts uses TypeScript objects to describe GraphQL selections. The object shape mirrors the GraphQL response shape, and the generated TypeScript types validate field names as you write.
Select fields
Use true to select a field. Nested objects select nested GraphQL fields.
import { createClient } from './generated';
const client = createClient();
const { data } = await client.query({
countries: {
name: true,
code: true,
languages: {
name: true,
},
},
});
data?.countries[0].languages[0].name;Pass arguments
Use a two-item tuple when a field needs GraphQL arguments. The first item is the argument object. The second item is the field selection.
const { data } = await client.query({
countries: [
{ filter: { continent: { eq: 'EU' } } },
{
name: true,
code: true,
languages: {
name: true,
},
},
],
});The same shape works for mutations:
await client.mutation({
createUser: [{ user: { name: 'Ada' } }, { id: true, name: true }],
});Alias fields
Use __alias when you need the same field more than once, or when the response key should be more specific than the schema field name.
const { data } = await client.query({
__alias: {
viewer: {
user: [{ login: 'meabed' }, { name: true, avatarUrl: true }],
},
maintainer: {
user: [{ login: 'octocat' }, { name: true }],
},
},
});
data?.viewer?.avatarUrl;
data?.maintainer?.name;The request above prints normal GraphQL aliases:
query ($v1: String!, $v2: String!) {
viewer: user(login: $v1) {
name
avatarUrl
}
maintainer: user(login: $v2) {
name
}
}Name operations
Use __name to set the generated GraphQL operation name.
generateQueryOp({
__name: 'CountryDashboard',
countries: {
name: true,
},
});Select scalar fields quickly
Use everything or __scalar: true to select scalar fields on a type.
import { everything } from './generated';
await client.query({
countries: {
...everything,
languages: {
...everything,
},
},
});everything selects scalar leaf fields only. You still choose object fields manually, which keeps large nested graphs explicit.
Exclude fields
When using __scalar, pass false for scalar fields you do not want.
await client.query({
countries: {
...everything,
id: false,
code: false,
},
});Syntax summary
| Need | Syntax |
|---|---|
| Select a field | { name: true } |
| Select nested fields | { country: { name: true } } |
| Pass arguments | { country: [{ code: 'CA' }, { name: true }] } |
| Alias a field | { __alias: { featured: { country: [{ code: 'CA' }, { name: true }] } } } |
| Name an operation | { __name: 'MyQuery', country: { name: true } } |
| Select scalar fields | { country: { __scalar: true } } |
| Exclude a scalar field | { country: { __scalar: true, id: false } } |