'How to create a GraphQL typed SDK from a Typescript schema object?
I have a code-first GraphQL API in which the GraphQLSchema is created like so:
import { GraphQLSchema } from 'graphql';
import { mutationType } from './mutation';
import { queryType } from './query';
const schema = new GraphQLSchema({
query: queryType,
mutation: mutationType,
});
export { schema };
I know how to generate a schema written in Schema Definition Language (SDL) with printSchema(schema).
Now I need a SDK to provide to clients of my API. My problem is that I can't find any library for generating a typed SDK from the schema.
The libraries I find like graphql-request, urql or apollo-client make you write the whole query without any type of syntax check.
import { gql, GraphQLClient } from 'graphql-request'
const query = gql` //
{ //
Movie(title: "Inception") { // I can write whatever I want
releaseDate // here and no transpilation
actors { // errors will appear.
name // I have no autocompletion
} // whatsoever.
} //
} //
`
const client = new GraphQLClient('https://api.graph.cool/simple/v1/movies', { headers: {} })
client.request(query, variables).then((data) => console.log(data))
I want to be able to do something like const client = new GraphQLClient(endpoint, schema, options);. And then use it like so await client.movie(title)({releaseDate: true, actors: {name: true}});. Not necessarily with that syntax, but I hope this gets the idea across. If I write rleaseDate I just want a red line under it in my IDE and a transpilation error if I run tsc.
I've found graphql-code-generator and I see that it can generate different things using the schema generated with printSchema(schema). But for the typescript-graphql-request plugin that can generate the SDK I want, it appears I would need to write an operation.graphql file myself, which is the first thing I want to avoid. The API, as I said, is code-first and everything is in the schema I talk about in the start. I don't want a second source of truth in that operation.graphql file.
Does what I want exist?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
