Interfaces¶
Like many type systems, GraphQL supports interfaces. An Interface is an abstract type that includes a certain set of fields that a type must include to implement the interface (read more here).
Code first¶
When using the code first approach, you define a GraphQL interface by creating an abstract class annotated with the @InterfaceType()
decorator exported from the @nestjs/graphql
.
Warning
TypeScript interfaces cannot be used to define GraphQL interfaces.
This will result in generating the following part of the GraphQL schema in SDL:
Now, to implement the Character
interface, use the implements
key:
Hint
The @ObjectType()
decorator is exported from the @nestjs/graphql
package.
The default resolveType()
function generated by the library extracts the type based on the value returned from the resolver method. This means that you must return class instances (you cannot return literal JavaScript objects).
To provide a customized resolveType()
function, pass the resolveType
property to the options object passed into the @InterfaceType()
decorator, as follows:
Schema first¶
To define an interface in the schema first approach, simply create a GraphQL interface with SDL.
Then, you can use the typings generation feature (as shown in the quick start chapter) to generate corresponding TypeScript definitions:
Interfaces require an extra __resolveType
field in the resolver map to determine which type the interface should resolve to. Let's create a CharactersResolver
class and define the __resolveType
method:
Hint
All decorators are exported from the @nestjs/graphql
package.