How to query your database using Prisma with NestJS #174
Replies: 11 comments 1 reply
-
Hi! Could you please take a look at my code? https://github.com/Guiradi/Sempapp-API First, I don't know why but prisma client and my nest models enums are not assignable (???) And, my nested relationships are in loop! One model needs that the other one loads his relationship and it turned into a cycle! I can't find this in Prisma documentation... Hope you could help me, this is my first project with Nest and Prisma and is for study only. Great article by the way, it helped me a lot! Thank you Guilherme |
Beta Was this translation helpful? Give feedback.
-
@Guiradi You are trying to assign the Prisma 1. Prisma `type` != GraphQL `class`Prisma /**
* Model User
*/
export type User = {
id: string
createdAt: Date
updatedAt: Date
email: string
password: string
firstname: string | null
lastname: string | null
role: Role
} Graphql @ObjectType()
export class User extends Model {
email: string;
firstname?: string;
lastname?: string;
role: Role;
posts: Post[];
@HideField()
password: string;
} 2. GraphQL Model contains relationshipsGraphql @ObjectType()
export class User extends Model {
email: string;
firstname?: string;
lastname?: string;
role: Role;
posts: Post[]; <- not available in the Prisma User type
@HideField()
password: string;
} It is similar for the I am not sure about the loop in nested relationships. Your code example is not available anymore for me to test. Thanks for reaching out! |
Beta Was this translation helpful? Give feedback.
-
Hi, Thanks for the nestjs prisma 2 starter template. I am prototyping with it for graphql. What puzzles me; how do I code an explicit many-to-many relation in the resolvers? Cheers, |
Beta Was this translation helpful? Give feedback.
-
Hi @johsthlm, take the following model Post {
id Int @id @default(autoincrement())
categories Category[]
}
model Category {
id Int @id @default(autoincrement())
posts Post[]
} For both models you create an entity class including the relation for the relation
import { Field, ObjectType } from '@nestjs/graphql';
import { Category } from './category.entity';
@ObjectType()
export class Post {
@Field(() => Int)
id: number;
@Field(() => [Category])
categories: Category[];
}
import { Field, ObjectType } from '@nestjs/graphql';
import { Post } from './post.entity';
@ObjectType()
export class Category {
@Field(() => Int)
id: number;
@Field(() => [Post])
posts: Post[];
} Now you have two options to fetch the relationship in the resolver
import { Resolver, Query, Mutation, Args } from '@nestjs/graphql';
import { Post } from './entities/post.entity';
@Resolver(() => Post)
export class ProductsResolver {
constructor(private readonly prisma: PrismaService) {}
@Query(() => Post, { name: 'post' })
findOne(@Args('id', { type: () => Int }) id: number) {
return this.prisma.post.findOne({
where: { id },
include: {
categories: true,
},
});
}
@Query(() => Post, { name: 'posts' })
findMany() {
return this.prisma.post.findMany({
include: {
categories: true,
},
});
}
}
import { Resolver, Query, Mutation, Args } from '@nestjs/graphql';
import { Post } from './entities/post.entity';
@Resolver(() => Post)
export class ProductsResolver {
constructor(private readonly prisma: PrismaService) {}
@Query(() => Post, { name: 'post' })
findOne(@Args('id', { type: () => Int }) id: number) {
return this.prisma.post.findOne({
where: { id },
});
}
@Query(() => Post, { name: 'posts' })
findMany() {
return this.prisma.post.findMany();
}
@ResolveField()
categories(@Parent() post: Post) {
return this.prisma.post.findOne({ where: { id: post.id } }).categories();
}
} Hopefully this answer helps you, let me know otherwise create a demo repo with the problem. Have a great day. |
Beta Was this translation helpful? Give feedback.
-
Thanks Marc, I tried your commented solution first. Then I wanted more control on the "connecting" attributed and followed this explicit schema of a relation table where I am stuck in creating a nice @ResolveField and also the mutation of creating the records building up a relation: model Post {
id Int @id @default(autoincrement())
title String
categories CategoriesOnPosts[]
}
model Category {
id Int @id @default(autoincrement())
name String
posts CategoriesOnPosts[]
}
model CategoriesOnPosts {
post Post @relation(fields: [postId], references: [id])
postId Int // relation scalar field (used in the `@relation` attribute above)
category Category @relation(fields: [categoryId], references: [id])
categoryId Int // relation scalar field (used in the `@relation` attribute above)
createdAt DateTime @default(now())
@@id([postId, categoryId])
} |
Beta Was this translation helpful? Give feedback.
-
I'm currently using Nestjs with Typeorm and in the model class I use
Example:
How would I do this with Prisma where there is an autogenerated model class? |
Beta Was this translation helpful? Give feedback.
-
@some-user123 when you work with Prisma you are defining the database model in the
model Product {
value Decimal @db.Decimal(2,2)
}
export class ProductEntity {
@ApiProperty({ type: Number, example: 1.23 })
value: number;
} Optional you can implement the generated type from Prisma on your entity like so import { Product } from '@prisma/client';
export class ProductEntity implements Product {
@ApiProperty({ type: Number, example: 1.23 })
value: number;
} I wrote about the duplication between Prisma Model and GraphQL API which also applies for REST. |
Beta Was this translation helpful? Give feedback.
-
Thanks for your reply! |
Beta Was this translation helpful? Give feedback.
-
Prisma returns your data as plain json objects. You have to return the correct values matching your Entity/Model of your response. Try it out with a simple response and you will see how it works. |
Beta Was this translation helpful? Give feedback.
-
Nice article, one question thought: Is there an way to create two prisma client with |
Beta Was this translation helpful? Give feedback.
-
Very useful, thanks. Is there any sample project which has different data shape & api shape using Nestjs, prisma, GraphQL in SDL first approach? |
Beta Was this translation helpful? Give feedback.
-
How to query your database using Prisma with NestJS
Learn how to setup a database with Prisma 2.0 and query data using NestJS.
https://notiz.dev/blog/how-to-connect-nestjs-with-prisma
Beta Was this translation helpful? Give feedback.
All reactions