apollo-server icon indicating copy to clipboard operation
apollo-server copied to clipboard

Ensure that the API is compatible with code generation

Open glasser opened this issue 3 years ago • 5 comments
trafficstars

We want TypeScript users to write code that statically checks that resolver types match schema types. The best way to do this in a schema-first approach is to use graphql-code-generator with typescript-resolvers. We would like to eventually (#6052) make sure our docs show this as the default way to build apps with Apollo Server, but that could be post-4.0 work. What we definitely want to do as part of 4.0.0 is ensure that there's nothing about the API that makes combining it with typescript-resolvers more awkward than it needs to be.

glasser avatar Mar 02 '22 19:03 glasser

While pairing with @glasser we decided we like this as a second type arg to the constructor new ApolloServer<MyContext, CodegenResolverTypes<MyContext>>({ ... })

trevor-scheer avatar Mar 22 '22 20:03 trevor-scheer

@glasser looks like I was thinking about this before :) ^

I can imagine two ways of typing your resolvers:

const resolvers: CodegenResolvers<MyContext> = {
  Query: { ... }
  // ...
};
const server = new ApolloServer<MyContext>({
  // ...
  resolvers,
})

OR

const server = new ApolloServer<MyContext, CodegenResolvers<MyContext>>({
  resolvers: {
    Query: { ... },
  },
});

I guess having the 2nd type argument allows users a bit more flexibility in how they want to define their resolvers and tell AS about that type. In the second example, the first implementation should also work (and AS can infer the 2nd arg based on the type of resolvers that's passed in).

trevor-scheer avatar Aug 22 '22 22:08 trevor-scheer

Hmm. How common do you think it is for people to be using codegen with a server small enough that you really want to be able to write resolvers inline?

glasser avatar Aug 22 '22 22:08 glasser

Fair point. Do you see a drawback to the 2nd option as far as the API goes? I don't feel strongly that it needs to be that way, but it does seem like a "superset" as far as the API goes.

trevor-scheer avatar Aug 22 '22 22:08 trevor-scheer

The only downside is that since TS generics are only positional, having too many generics (even with defaults) can get unwieldy. So if we come up with a third one later, you need to put in the default for this one in order to use the third one.

glasser avatar Aug 22 '22 23:08 glasser

This was recently added to the AS4 docs: https://github.com/apollographql/apollo-server/pull/6904

hwillson avatar Sep 21 '22 16:09 hwillson