Wrong type for one-to-many field in user.model.ts
✌️
When querying one-to-many, for example, User with Articles will be an empty array if user does not have any articles but in the user.model.ts model the articles field has a type like: Array<Article> | null | undefined but I need the array fields to always be of type Array but without null and undefined since prisma in this case returns just an empty array.
So from this:
@Field(() => [Article], {nullable:true})
articles?: Array<Article>;
I need to do this:
@Field(() => [Article], {nullable:false})
articles: Array<Article>;
Example code
const users = await this.prisma.user.findFirst({
select: {
id: true,
articles: {
select: {
id: true,
},
},
},
});
/*
users = {
id: 1,
articles: [],
}
*/
Example user.model.ts
Note that the articles field is of type undefined and nullable: true
@ObjectType()
export class User {
@Field(() => Int, {nullable:false})
id!: number;
@Field(() => [Article], {nullable:true})
articles?: Array<Article>;
}
Example schema.prisma
model User {
id Int @id @default(autoincrement())
articles Article[]
}
model Article {
id Int @id @default(autoincrement())
title String @unique
authorId Int
author User @relation(fields: [authorId], references: [id])
}
You need both typescript and graphql types as non-nullable?
In case of typescript this will make prisma types and generated types incompatible:
Property articles is not generated in prisma User type.
@unlight In my case, I need that articles as non-nullable only in the graphql output type, so that I could resolve articles with @ResolveField()