Reputation: 247
I'm using type-graphql in conjunction with typeorm, apollo-server-express and postgreSQL. I have a User and a Customer entity in a 1:n relationship, meaning one user can have multiple customers.
I can create users and customers just fine, but when attempting to retrieve the user associated to a customer using Apollo Server playground, I get an error message stating "Cannot return null for non-nullable field Customer.user."
When I check the database, the associated user id on the customer table is definitely not null (see attached image).
query {
customers {
customerId
customerName
user {
userId
}
}
}
Does anyone know what I'm doing wrong?
User.ts
import { Field, ID, ObjectType } from "type-graphql";
import { BaseEntity, Column, Entity, OneToMany, PrimaryGeneratedColumn } from "typeorm";
import { Customer } from "./Customer";
@ObjectType()
@Entity("users")
export class User extends BaseEntity {
@Field(() => ID)
@PrimaryGeneratedColumn("uuid")
userId: string;
@Field()
@Column({ unique: true })
email: string;
@Column({ nullable: false })
password: string;
@Field(() => Customer)
@OneToMany(() => Customer, customer => customer.user)
customers: Customer[]
}
Customer.ts
import { Field, ID, ObjectType } from "type-graphql";
import { BaseEntity, Column, Entity, ManyToOne, PrimaryGeneratedColumn } from "typeorm";
import { User } from "./User";
@ObjectType()
@Entity("customers")
export class Customer extends BaseEntity {
@Field(() => ID)
@PrimaryGeneratedColumn("uuid")
customerId: string;
@Field()
@Column()
customerName: string;
@Field(() => User)
@ManyToOne(() => User, user => user.customers)
user: User;
}
CustomerResolver.ts
export class CustomerResolver {
@Query(() => [Customer])
async customers():Promise<Customer[]> {
try {
return await Customer.find();
} catch (error) {
console.log(error);
return error;
}
}
....
Setup / Version
Upvotes: 1
Views: 318
Reputation: 12127
You should write a @FieldResolver
which will fetch customers
based on root user
data.
https://typegraphql.com/docs/resolvers.html#field-resolvers
Upvotes: 1
Reputation: 5814
In your resolver change the find
operation like below:
return Customer.find({
relations: ["user"]
});
Upvotes: 1