Generating SDL

Warning This chapter applies only to the code first approach.

To manually generate a GraphQL SDL schema (i.e., without running an application, connecting to the database, hooking up resolvers, etc.), use the GraphQLSchemaBuilderModule.

  1. async function generateSchema() {
  2. const app = await NestFactory.create(GraphQLSchemaBuilderModule);
  3. await app.init();
  4. const gqlSchemaFactory = app.get(GraphQLSchemaFactory);
  5. const schema = await gqlSchemaFactory.create([RecipesResolver]);
  6. console.log(printSchema(schema));
  7. }

Hint The GraphQLSchemaBuilderModule and GraphQLSchemaFactory are imported from the @nestjs/graphql package. The printSchema function is imported from the graphql package.

Usage

The gqlSchemaFactory.create() method takes an array of resolver class references. For example:

  1. const schema = await gqlSchemaFactory.create([
  2. RecipesResolver,
  3. AuthorsResolver,
  4. PostsResolvers,
  5. ]);

It also takes a second optional argument with an array of scalar classes:

  1. const schema = await gqlSchemaFactory.create(
  2. [RecipesResolver, AuthorsResolver, PostsResolvers],
  3. [DurationScalar, DateScalar],
  4. );

Lastly, you can pass an options object:

  1. const schema = await gqlSchemaFactory.create([RecipesResolver], {
  2. skipCheck: true,
  3. orphanedTypes: [],
  4. });
  • skipCheck: ignore schema validation; boolean, defaults to false
  • orphanedTypes: list of classes that are not explicitly referenced (not part of the object graph) to be generated. Normally, if a class is declared but isn’t otherwise referenced in the graph, it’s omitted. The property value is an array of class references.