I would like to use interface resolver as described in official documentation of NestJS and I have created following code to try it out.
Models are in file models.ts:
import { Field, ID, InterfaceType, ObjectType } from '@nestjs/graphql';
@ObjectType()
export class Task {
@Field((type) => ID)
id: string;
@Field()
description: string;
}
@InterfaceType()
export abstract class ITaskAssignable {
@Field((type) => [Task])
tasks: Task[]
}
@ObjectType({ implements: () => [ITaskAssignable] })
export class Person implements ITaskAssignable {
@Field((type) => ID)
id: string;
@Field()
name: string;
@Field((type) => [Task])
tasks: Task[]
}
Resolvers with mock logic are in file resolvers.ts:
import { Args, Info, Parent, Query, ResolveField, Resolver } from '@nestjs/graphql';
import { ITaskAssignable, Person, Task } from './models';
@Resolver(of => Task)
export class TaskResolver {
constructor() { }
@Query(returns => Task)
async task(@Args('id') id: string): Promise<Task> {
return { id, description: 'something' };
}
}
@Resolver(of => Person)
export class PersonResolver {
constructor() { }
@Query(returns => Person)
async person(@Args('id') id: string): Promise<Person> {
return { id, name: 'John Doe' } as Person;
}
}
@Resolver(of => ITaskAssignable)
export class ITaskAssignableResolver {
@ResolveField(returns => [Task])
async tasks(@Parent() parent, @Info() info): Promise<Task[]> {
return [{ id: 'example-id', description: 'something' }];
}
}
App module and Task module are in one file modules.ts:
import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';
import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { PersonResolver, TaskResolver } from './resolvers';
@Module({
providers: [PersonResolver, TaskResolver],
})
export class TaskModule { }
@Module({
imports: [
TaskModule,
GraphQLModule.forRoot<ApolloDriverConfig>({
driver: ApolloDriver,
autoSchemaFile: 'schema.gql',
}),
],
})
export class AppModule { }
Last file is main.ts:
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './modules';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe());
await app.listen(3000, 'localhost');
console.log(`Application is running on: ${await app.getUrl()}`);
}
bootstrap();
Thetasks field is auto-registered for Person model and can be queried but throws error: "Cannot return null for non-nullable field Person.tasks.",
I have several times read through documentation and tried to find if someone encounter similar problem, but I didn't found solution.