Issue
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?
Solution
Alright! So I found what I was looking for: graphql-zeus
The command zeus [path to SDL file] --typescript --node
generates an SDK I can provide to the clients that will use the API, and they can use the SDK like so:
import { Chain } from "[SDK generated]";
Chain(`example.com/graphql`, {
headers: {
'Authorization': 'Bearer 00112233445566778899',
'Content-Type': 'application/json',
},
})('mutation')({
createUser: [{
username: newUsername,
biography: newBio,
picture: newPicture,
},
{ id: true, username: true }]
})
.catch(error => {
// Do something
});
And mutation
, the operation createUser
and it's parameters are typed. Meaning I will get transpilation errors and the IDE will tell me what I can type in each field.
Answered By - BlueSialia
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.