Skip to content

Code-first GraphQL

A deep dive into the ts-graphql starter: building a schema from decorators, resolvers as providers, arguments and field resolvers, method interceptors on resolver methods, and serving REST next to GraphQL on one module graph.

7 min read Source

Source: ts-graphql

This starter runs a GraphQL endpoint and two REST endpoints from the same module graph, sharing the same services. It is the smallest application that shows how @typeix/resty-graphql differs from the controller-based world: a resolver is not a controller, and a field is not a route.

It replaces an earlier type-graphql implementation, so the migration table at the end maps the old API onto the new one.

Project layout

src
├─ app.module.ts                        # rest controllers + resolvers in one graph
├─ bootstrap.ts                         # pipeServer → pipeGraphQL → pipeSwagger
├─ data
│  ├─ user.entity.ts                    # @ObjectType + @ApiSchema, @Field + @ApiProperty
│  └─ permission.entity.ts
├─ services
│  ├─ user.service.ts                   # in-memory data
│  └─ permission.service.ts
├─ controllers/rest
│  ├─ user.controller.ts                # GET /users
│  └─ permission.controller.ts          # GET /permissions
├─ controllers/graphql
│  ├─ user.resolver.ts                  # Query users, field permissions
│  ├─ permission.resolver.ts            # Query permissions
│  ├─ logger.interceptor.ts             # @LogOutput, a method interceptor
│  └─ test/graphql-test-server.ts       # helper: real listener for tests
└─ swagger.spec.ts

The module graph

@RootModule({
  imports: [],
  controllers: [UserController, PermissionController],
  providers: [UserService, PermissionService, UserResolver, PermissionResolver],
  shared_providers: [/* Logger factory */]
})
export class AppModule {
}

Resolvers are listed under providers, not controllers. That single line explains most of the model:

  • A controller is bound to a route by the router. A resolver has no route — it is a provider the GraphQL server calls when a query asks for a field.
  • Because it is a provider, it is resolved through the injector and can inject services, the logger and request-scoped values exactly like any other class.
  • pipeGraphQL scans the module graph for resolver metadata, so a resolver that is not registered as a provider never reaches the schema.

Types from decorators

@ObjectType()
@ApiSchema({name: "User"})
export class User {

  @Field()
  @ApiProperty({example: 1})
  id: number;

  @Field()
  @ApiProperty({example: "John"})
  firstName: string;

  @Field(() => [Permission])
  @ApiProperty({type: () => [Permission]})
  permissions: Array<Permission> = [];
}

The class carries two sets of decorators, one per consumer:

  • @Field/@ObjectType feed the GraphQL schema.
  • @ApiSchema/@ApiProperty feed the OpenAPI document for the REST controllers.

They coexist because both are metadata only. A single model therefore serves both protocols without a mapping layer — the same instance the resolver returns is the one the REST controller serialises.

Why some types are a thunk

@Field(() => [Permission])                  // thunk: array of a class
permissions: Array<Permission> = [];

@Field()                                    // no thunk: type is in the metadata
firstName: string;

The emitted design:type metadata stores the constructor for a property. For Array<Permission> it can only store Array, so the element type has to be supplied explicitly with () => [Permission]. The rule of thumb:

Declaration Needs a thunk
string, number, boolean no
Permission (class) no, but a thunk is clearer when classes reference each other
Array<Permission> yes
Promise<User> yes
string \| null yes, plus nullable: true

Queries and arguments

@Injectable()
@Resolver(() => User)
export class UserResolver {

  @Inject() private userService: UserService;
  @Inject() private permissionService: PermissionService;
  @Inject() private logger: Logger;

  @Query(() => [User])
  @LogOutput("Logging UserResolver.users")
  users(
    @Args({name: "firstName", type: String, nullable: true}) firstName: string
  ): Array<User> {
    return this.userService.findByName(firstName);
  }

  @ResolveField(() => [Permission])
  @LogOutput("Logging UserResolver.users.permissions")
  permissions(@Parent() user: User): Array<Permission> {
    return this.permissionService.find(user);
  }
}
  • @Resolver(() => User) associates the class with the User type. The thunk defers the lookup, so a resolver and its type can reference each other without a circular import at decoration time.
  • @Query(() => [User]) produces users(firstName: String): [User!]!.
  • @Args describes one argument; type: String is needed because the parameter type alone is not available at runtime, and nullable: true turns the argument into an optional one.
  • @Parent receives the object the parent query resolved — here, the User whose permissions are being asked for. This is how a field resolver avoids the resolver having to know where the parent came from.

PermissionResolver is the minimal case: no type binding, one query, one injected service.

@Injectable()
@Resolver()
export class PermissionResolver {

  @Inject() private permissionService: PermissionService;

  @Query(() => [Permission])
  permissions(): Array<Permission> {
    return this.permissionService.find();
  }
}

What a request looks like

query {
  users(firstName: "John") {
    id
    firstName
    permissions { action }
  }
}
  1. The GraphQL server parses the document and validates it against the schema.
  2. It resolves users: the injector hands it the UserResolver instance, the argument is coerced, and findByName runs.
  3. For each returned User, the selection set asks for permissions, so UserResolver.permissions is invoked per object with that object as @Parent.
  4. Errors thrown inside a resolver become GraphQL errors for that field only; sibling fields still resolve.

Field resolvers are the N+1 trap

permissions(@Parent() user) runs once per user. With the in-memory service that is free; with a database it becomes one query per row. Batch the lookup (collect the parents, run one query, map the results back) or cache per request. This starter is the place to see the shape of the problem; a production resolver needs the batching step.

Method interceptors on resolvers

Resolvers are providers, so the DI method-interceptor machinery applies to them unchanged:

@Injectable()
class LoggerInterceptor implements Interceptor {
  @Inject() private logger: Logger;

  async invoke(method: Method): Promise<any> {
    let result = await method.invoke();
    this.logger.debug([
      `Injected arguments: ${this.prettyPrint(method.methodArgs)}`,
      `Result ${this.prettyPrint(result)}`,
      `With decorator args: ${this.prettyPrint(method.decoratorArgs)}`
    ].join("\n"));
    return result;
  }
}

export function LogOutput(value) {
  return createMethodInterceptor(LogOutput, LoggerInterceptor, {value});
}

@LogOutput("…") on a resolver method logs the resolved arguments, the result and the decorator options. This works on any injectable method — controllers, resolvers, socket handlers — not just routes, which is why the same decorator could be moved onto a service method.

Serving REST next to GraphQL

async function bootstrap() {
  const server = createServer();
  await pipeServer(server, AppModule);
  await pipeGraphQL(server, AppModule, {
    path: "/graphql",
    sdl: true,
    title: "Resty starter GraphQL"
  });
  await pipeSwagger(server, AppModule, {
    path: "/docs",
    yaml: true,
    info: {title: "Resty starter GraphQL", version: "1.0.0"}
  });
  server.listen(8080);
}
Route Content
POST /graphql queries and mutations
GET /graphql?query=… queries only
GET /graphql with Accept: text/html playground
GET /graphql/schema.graphql SDL, because sdl: true
GET /users, GET /permissions REST controllers
GET /docs OpenAPI for the REST routes only

Swagger documents the controllers, not the GraphQL operations: the GraphQL handler is piped onto the server, not registered as a controller, so it has no route definition to document. The GraphQL endpoint publishes its own SDL and playground instead.

Tests

File Kind What it proves
controllers/graphql/test/*.integration-spec.ts integration real HTTP queries against a real listener
controllers/rest/test/*.spec.ts unit controller behaviour
swagger.spec.ts build-time only the REST routes and both components appear

The GraphQL tests bind port 0 and post JSON, because pipeGraphQL needs a server.Server and FakeServerApi keeps its own instance private:

const server = createServer();
await pipeServer(server, AppModule);
await pipeGraphQL(server, AppModule, {path: "/graphql"});
await new Promise<void>(resolve => server.listen(0, resolve));
const {port} = server.address() as AddressInfo;

The sibling starter GraphQL over TypeORM shows the alternative: GraphQLModule.printSchema(AppModule) asserts the schema with no server at all.

Pitfalls

Numeric fields become Float!, not ID!

@typeix/resty-graphql exports GraphQLID, GraphQLInt and the other scalar instances, but the type registry rejects GraphQLScalarType instances (custom scalar … is not supported). An id: number property therefore maps to Float!. Declare ids as number and accept Float, or expose them as String with an explicit field type. Do not reach for @Field(() => ID).

  • Resolvers must be providers. Putting a resolver in controllers compiles and boots but the schema stays empty.
  • @Field() alone is not enough for arrays, promises or unions — see the thunk table above.
  • Every field is non-null by default. A resolver that returns null for a non-null field produces an execution error, not an empty field. Mark the nullable ones explicitly.
  • Decorator order does not matter, but both decorator families must be applied to the same property if you want both protocols to see it.

Migrating from type-graphql

type-graphql @typeix/resty-graphql
@Resolver(User) @Resolver(() => User)
@FieldResolver() + @Root() @ResolveField(() => Type) + @Parent()
@Arg("firstName", {nullable: true}) @Args({name: "firstName", type: String, nullable: true})
@Field(() => ID) @Field() on a number (maps to Float)
GraphQLController + buildSchema pipeGraphQL after pipeServer

The resolver still injects services, still returns entities, and the schema is still generated from decorators — what disappears is the controller that hosted buildSchema and the separate schema file.

Next: GraphQL over TypeORM puts this schema on a database.