0
0
GraphQLquery~10 mins

Prisma ORM with GraphQL

Choose your learning style9 modes available
Introduction

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.

When building a web app that needs to get or save data from a database.
When you want to ask for only specific data fields to reduce loading time.
When you want to keep your database code clean and easy to understand.
When you want to connect your database with a frontend app using a flexible API.
When you want to avoid writing complex SQL queries by hand.
Syntax
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.

Examples
This query fetches all users from the database.
GraphQL
type Query {
  allUsers: [User!]!
}

// Resolver example
allUsers: async () => {
  return await prisma.user.findMany();
}
This mutation adds a new user with a name and email.
GraphQL
type Mutation {
  createUser(name: String!, email: String!): User!
}

// Resolver example
createUser: async (_, args) => {
  return await prisma.user.create({ data: args });
}
This query fetches one user by their unique ID.
GraphQL
type Query {
  userById(id: ID!): User
}

// Resolver example
userById: async (_, args) => {
  return await prisma.user.findUnique({ where: { id: Number(args.id) } });
}
This mutation deletes a user by ID and returns the deleted user data.
GraphQL
type Mutation {
  deleteUser(id: ID!): User
}

// Resolver example
deleteUser: async (_, args) => {
  return await prisma.user.delete({ where: { id: Number(args.id) } });
}
Sample Program

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
// 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();
OutputSuccess
Important Notes

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.

Summary

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.