prismake / typegql

Create GraphQL schema with TypeScript classes.
https://prismake.github.io/typegql/
MIT License
423 stars 21 forks source link

Example of having resolvers in separate files #52

Closed jdolle closed 6 years ago

jdolle commented 6 years ago

In my experience, resolvers can get pretty large. Because of this, I am afraid defining all resolvers in the schema class will become unwieldy. What is the best approach to moving a resolver to a separate file, then using it in the schema class?

If there is an agreement on such a process, I would be happy to amend the documentation. Currently I have found one approach that seems promising:

import doSomething from "..."

@Mutation()
  public doSomething(
    @Inject(doSomething) value: boolean,
  ): boolean {
    return value
  }
ghost commented 6 years ago

I would also like to know this as well. We want to define our schemas in one package that also our consumers use. Then define the resolvers in our private server code. If that's at all possible.

capaj commented 6 years ago

I don't know if I am not missing something, but you certainly can have a SchemaClass which exposes your internal class. So:

const myUberPrivateSchema = {
  a() {...}
}

// somewhere else
@SchemaRoot()
export class Schema { 
  @Mutation()
  public a() {
    return myUberPrivateSchema.a()
  }
}
pie6k commented 6 years ago

Exactly for reason you've described, single schema can have multiple schema roots.

Example:

import { SchemaRoot, Query, Mutation, compileSchema } from "typegql";

@SchemaRoot()
export class UserSchemaRoot {
  @Query()
  allUsers() {}
}

@SchemaRoot()
export class UserMutationsSchemaRoot {
  @Mutation()
  registerUser() {}
}

@SchemaRoot()
export class ProductSchemaRoot {
  @Query()
  allProducts() {}
}

const finalSchema = compileSchema([UserSchemaRoot, UserMutationsSchemaRoot, ProductSchemaRoot])

As seen, final schema is composed from many 'root' classes. Obviously, those classes can be defined in different files and imported.

Technically, you're not importing resolver itself, but you're able to divide your schema logic into many parts and it'd scale horizontally even for huge schema allowing you to have many small, easy to understand files.

Let me know if that solves your problem.

jdolle commented 6 years ago

Works for my purposes. Thanks