prisma-nestjs-graphql icon indicating copy to clipboard operation
prisma-nestjs-graphql copied to clipboard

Wrong type for one-to-many field in user.model.ts

Open nonamich opened this issue 2 years ago • 2 comments

✌️

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])
}

nonamich avatar May 19 '23 02:05 nonamich

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 avatar Jun 03 '23 17:06 unlight

@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()

anandakelvin avatar Jul 08 '23 18:07 anandakelvin