Creating a Prisma Database for GraphQL

Get the full GraphQL series here

If you’re just joining the series start at the start-prisma-setup branch

In this post we’re going to setup an actual database using Prisma and MySQL. This could be done with Postgres or whatever you need. We’re going to use SQLite now because it’s the easiest to setup. We’ll cover setting up a Docker db, or Mongo, or whatever in a future tutorial. Note: If you’re using a data source that Prisma doesn’t support you can still use Graphql, you would just have a bit more work.

Learn to code with our beginner friendly tutorials on programming, Linux, Docker, and more

In order to work with Prisma we need to install it via npm

$ npm install @prisma/cli --save-dev

Now complete the following steps:

  1. Create a prisma/ directory in the root of your project
  2. Create a schema.prisma file inside the prisma directory.

Insert the following code into your prisma/schema.prisma

datasource db {
    provider = "sqlite"
    url      = "file:./dev.db"
}

generator client {
    provider = "prisma-client-js"
}

model User {
    id        Int      @id @default(autoincrement())
    createdAt DateTime @default(now())
    firstName String
    email     String
}

In the code above we’re setting the location of the datasource. Since we’re using SQLite the endpoint/source is just the file.

generator client allows you to set the type of code to use. You can use Typescript or whatever other options they have.

model User is where we define the table schema of the User. We’re basically designing our SQL database with tables, columns, data types, etc…

Now we need to run some terminal commands to allow Prisma to setup the database. Proceed with the following commands in the root dir of your project:

$ npx prisma migrate save --experimental

When prompted, select YES to create a new SQLite database.

Name the migration. We’re “adding a user” so “addUser” is fine for migration name

now run the following two commands:

$ npx prisma migrate up --experimental
$ npx prisma generate

These three commands usually come as a package deal. They create a “history” of the evolution of your database schema, and then update the tables to match your schema.prisma file, along with any other setup necessary.

Prisma is a replacement for traditional ORMS, meaning it provides us easy access to the database. We get things like findOne, findMany, deleteOne, etc… but we need a way to access the functions Prisma provides. How we do that is by attaching a Prisma object to the context which is the third argument in your resolver functions.

context is an object that every resolver can read and write to, so this is a great place to put the prisma code. Let’s do that now with below. First, import PrismaClient in src/index.js then create a prisma object equal to the Prisma client:

const { PrismaClient } = require('@prisma/client')
const prisma = new PrismaClient()

Now that we have all our Prisma functions accessible via the “prisma” object, let’s stick the prisma object into the context. update the server constant in the src/index.js to look like below:

const server = new GraphQLServer({
  typeDefs,
  resolvers,
  context: {
    prisma,
  }
})

Now that we’re using Prisma and SQLite let’s try to use it to query the database for all the existing users. (There won’t be any because we only have a hard-coded array of users and an empty database… Change your resolvers constant to look like below:

const resolvers = {
  Query: {
    helloWorld: () => `Hello World! What a day!`,
    users: async (parent, args, context, info) => {
      return context.prisma.user.findMany();
    },
// ...

If you put a console.log(context) Or better yet set a breakpoint in the users function to see what exactly is provided in the context argument you should see something like this:

Those are all the functions prisma provides just for the “user”. They will do this for anything you add to the schema, like posts, likes, etc… Now let’s restart the server and run the following query in the playground:

query {
  users {
    firstName
    email
  }
}

Now let’s refactor by moving our typeDefs into a separate file. change the const server portion in src/index.js to look like below:

const server = new GraphQLServer({
  typeDefs: './src/schema.graphql',
  resolvers,
  //...

Now take everything in the const typeDefs and move it into the ./src/schema.graphql file:

type Query {
  helloWorld: String!
  users: [User!]!
  user(userId: ID!): User
}

type User {
    id: ID!
    firstName: String!
    email: String!
}

and finally remove the const typeDefs from the index.js file.

Restart the server and test everything still works.

Final code is in the “done-prisma-setup” branch

So now we have an empty database that needs to be populated. Let’s do that in the next tutorial.

Want More Tutorials?

Get our best crash courses and tutorials

(Source Code Provided)

Leave a Comment

Your email address will not be published. Required fields are marked *

want more details?

Fill in your details and we'll be in touch

%d bloggers like this: