Prisma ORM helps you easily work with databases using simple code. GraphQL lets you ask for exactly the data you want. Together, they make fetching and changing data smooth and clear.
Prisma ORM with GraphQL
type Query {
allUsers: [User!]!
}
type Mutation {
createUser(name: String!, email: String!): User!
}
type User {
id: ID!
name: String!
email: String!
}
// In your resolver file (JavaScript/TypeScript):
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();
const resolvers = {
Query: {
allUsers: async () => {
return await prisma.user.findMany();
},
},
Mutation: {
createUser: async (_, args) => {
return await prisma.user.create({ data: args });
},
},
};The GraphQL schema defines what data you can ask for or change.
Resolvers connect GraphQL queries and mutations to Prisma database commands.
type Query {
allUsers: [User!]!
}
// Resolver example
allUsers: async () => {
return await prisma.user.findMany();
}type Mutation {
createUser(name: String!, email: String!): User!
}
// Resolver example
createUser: async (_, args) => {
return await prisma.user.create({ data: args });
}type Query {
userById(id: ID!): User
}
// Resolver example
userById: async (_, args) => {
return await prisma.user.findUnique({ where: { id: Number(args.id) } });
}type Mutation {
deleteUser(id: ID!): User
}
// Resolver example
deleteUser: async (_, args) => {
return await prisma.user.delete({ where: { id: Number(args.id) } });
}This program defines a simple GraphQL schema and resolvers using Prisma ORM. It shows fetching all users, adding a new user, and fetching all users again to see the change.
// GraphQL schema const { gql } = require('apollo-server'); const typeDefs = gql` type User { id: ID! name: String! email: String! } type Query { allUsers: [User!]! } type Mutation { createUser(name: String!, email: String!): User! } `; // Resolvers const { PrismaClient } = require('@prisma/client'); const prisma = new PrismaClient(); const resolvers = { Query: { allUsers: async () => { return await prisma.user.findMany(); }, }, Mutation: { createUser: async (_, args) => { return await prisma.user.create({ data: args }); }, }, }; // Example usage (simulate calling resolvers) async function runExample() { console.log('Users before:'); let usersBefore = await resolvers.Query.allUsers(); console.log(usersBefore); console.log('\nCreating a new user...'); let newUser = await resolvers.Mutation.createUser(null, { name: 'Alice', email: 'alice@example.com' }); console.log(newUser); console.log('\nUsers after:'); let usersAfter = await resolvers.Query.allUsers(); console.log(usersAfter); } runExample();
Prisma ORM automatically generates database queries, so you don't write SQL directly.
GraphQL lets clients ask for only the data they need, which can improve app speed.
Remember to handle errors in real apps, like when a user already exists or input is invalid.
Prisma ORM and GraphQL work together to make database access easy and flexible.
Define your data types and operations in GraphQL schema, then connect them to Prisma in resolvers.
This setup helps build clean, efficient APIs for apps that need database data.
Practice
Solution
Step 1: Understand Prisma ORM's purpose
Prisma ORM acts as a tool to simplify database operations by providing an easy way to query and manage data.Step 2: Differentiate Prisma from GraphQL schema and frontend roles
GraphQL schema defines data types and operations, while frontend styling is unrelated to Prisma's role.Final Answer:
To manage database access and queries easily -> Option DQuick Check:
Prisma ORM = database access tool [OK]
- Confusing Prisma with GraphQL schema definition
- Thinking Prisma manages frontend UI
- Assuming Prisma handles HTTP requests
Solution
Step 1: Recall Prisma Client import syntax
The official Prisma Client is imported using ES module syntax: import { PrismaClient } from '@prisma/client';Step 2: Identify incorrect import forms
Options B, C, and D use wrong package names or destructuring that Prisma does not support.Final Answer:
import { PrismaClient } from '@prisma/client'; -> Option CQuick Check:
Correct Prisma import = import { PrismaClient } from '@prisma/client'; [OK]
- Using wrong package name like 'prisma-client'
- Incorrect destructuring of PrismaClient
- Mixing CommonJS require with ES import incorrectly
const users = await prisma.user.findMany({ where: { active: true } });
return users;
What does this resolver return?Solution
Step 1: Analyze the Prisma query filter
The query uses findMany with a where clause filtering users where active equals true.Step 2: Understand the result of the query
It returns only users whose active field is true, excluding inactive users.Final Answer:
Only users with active set to true -> Option BQuick Check:
findMany with where active:true = filtered users [OK]
- Assuming it returns all users ignoring filter
- Thinking it causes an error without schema check
- Believing it always returns empty list
const newUser = prisma.user.create({
data: {
name: 'Alice'
}
});
return newUser;
What is the likely cause of the error?Solution
Step 1: Check asynchronous Prisma call
prisma.user.create returns a Promise, so it needs await to resolve before returning.Step 2: Identify missing await causing error
Without await, newUser is a Promise, not the created user object, causing issues in return.Final Answer:
Missing await before prisma.user.create call -> Option AQuick Check:
Async Prisma calls need await [OK]
- Forgetting to await async Prisma methods
- Assuming create returns data synchronously
- Confusing create with findMany usage
Solution
Step 1: Understand Prisma's include option
Using include: { posts: true } fetches related posts along with the user in one query.Step 2: Compare options for fetching user with posts
const user = await prisma.user.findUnique({ where: { id }, include: { posts: true } }); uses findUnique with include correctly; const user = await prisma.user.findMany({ where: { id }, select: { posts: false } }); excludes posts; const user = await prisma.post.findMany({ where: { userId: id } }); fetches posts only; const user = await prisma.user.findUnique({ where: { id } }); const posts = await prisma.post.findMany({ where: { userId: id } }); fetches separately, not in one query.Final Answer:
const user = await prisma.user.findUnique({ where: { id }, include: { posts: true } }); -> Option AQuick Check:
Include fetches relations in one query [OK]
- Using findMany instead of findUnique for single user
- Not using include to fetch related posts
- Fetching posts separately causing extra queries
Ready to prove it?
Pass the test and this pattern moves unknown
