egoist / ideas

💡ideas / thoughts / polls from egoist
100 stars 2 forks source link

Automatic SDK generation for GraphQL API #12

Open egoist opened 4 years ago

egoist commented 4 years ago

The problem

When accessing a GraphQL API, you typically do this:

apolloClient.mutate(gql`
  mutation MyMutation($name: String!, $password: $String!) {
    insert_user(objects: [{name: $name, password: $password}]) {
      returning {
        id
      }
    }
  }`,
  variables: {
    name: 'kevin',
    password: 'xxx'
  }
)

It's verbose, but if you also use TypeScript, a decent amount of manual type declarations are needed for type safety and that makes it even more verbose:

type OperationResult = {
  insert_user: {
    returning: Array<{ id: string }>
  }
}

type OperationVariables = {
  name: string
  password: string
}

apolloClient.mutate<OperationResult, OperationVariables>(gql`
  mutation MyMutation($name: String!, $password: $String!) {
    insert_user(objects: [{name: $name, password: $password}]) {
      returning {
        id
      }
    }
  }`,
  variables: {
    name: 'kevin',
    password: 'xxx'
  }
)

The solution

I wonder if it's possible/practical to generate a JS/TS/Go SDK with built-in types from a random GraphQL endpoint, given that you are able to access its schema file.

So instead of using DSL, you use an actual language instead:

const client = require('./generated-client')

await client.insert_user({
  objects: [{ name: 'kevin', password: 'xxx' }],
  select: {
    returning: {
      id: true
    }
  }
})

And it's type-safe by default.

uetchy commented 4 years ago

I like this idea. I’ve made something like that but for REST API. For REST API there’s no way to obtain API scheme so I failed to make it really convenient. https://github.com/uetchy/MuffledAPI

GraphQL would play nice with API client generator.

egoist commented 4 years ago

https://github.com/graphql-editor/graphql-zeus is exactly what I was talking about 😮

egoist commented 4 years ago

Here's a more low-level library, only for generating typescript typings: https://graphql-code-generator.com/docs/getting-started/

egoist commented 4 years ago

Turns out graphql-code-generator can also generate a full client, you just need to combine multiple plugins: https://github.com/graphile/starter/blob/master/%40app/graphql/codegen.yml

egoist commented 4 years ago

A list of solutions: https://twitter.com/HasuraHQ/status/1222197037459890176