Back to Prisma1

Overview

docs/1.9/04-Reference/08-Prisma-Bindings/01-Overview.md

1.34.123.6 KB
Original Source

Overview

prisma-binding is a dedicated GraphQL binding for Prisma GraphQL APIs. Think of it like an auto-generated SDK for Prisma services:

Note: If you're curious about this topic, you can read the following two blog posts:

prisma-binding provides a convenience layer for building GraphQL servers on top of Prisma services. In short, it simplifies implementing your GraphQL resolvers by delegating execution of queries (or mutations) to the API of the underlying Prisma database service. Rather than writing SQL or accessing a NoSQL database API like MongoDB inside your resolvers, most of your resolver will be implemented as simple one-liners.

Example

Consider the following application schema for your GraphQL server:

graphql
# import Post from "./generated/prisma.graphql"

type Query {
  posts: [Post!]!
  post(id: ID!): Post
  description: String!
}

type Mutation {
  createDraft(title: String!, text: String): Post
  deletePost(id: ID!): Post
  publish(id: ID!): Post
}

This is how the corresponding resolvers are implemented with a Prisma binding available as a db object on ctx:

js
const resolvers = {
  Query: {
    posts(parent, args, ctx, info) {
      return ctx.db.query.posts({ }, info)
    },
    post(parent, args, ctx, info) {
      return ctx.db.query.post({ where: { id: args.id } }, info)
    },
  },
  Mutation: {
    createDraft(parent, { title, text }, ctx, info) {
      return ctx.db.mutation.createPost(
        {
          data: {
            title,
            text,
          },
        },
        info,
      )
    },
    deletePost(parent, { id }, ctx, info) {
      return ctx.db.mutation.deletePost({ where: { id } }, info)
    },
    publish(parent, { id }, ctx, info) {
      return ctx.db.mutation.updatePost(
        {
          where: { id },
          data: { isPublished: true },
        },
        info,
      )
    },
  },
}

Note: To learn more about this particular example, check out this tutorial.

Using Prisma bindings to build GraphQL servers with Prisma

Here is how it works:

  1. Create your Prisma service by defining data model
  2. Download generated the Prisma database schema prisma.graphql (contains the full CRUD API)
  3. Define your application schema, typically called schema.graphql
  4. Instantiate Prisma with information about your Prisma service (such as its endpoint and the path to the database schema definition)
  5. Implement the resolvers for your application schema by delegating to the underlying Prisma service using the generated delegate resolver functions

Note: If you're using a GraphQL boilerplate project (e.g. with graphql create), the Prisma binding will already be configured and a few example resolvers implemented for you. You can either try the dynamic binding (e.g. in the node-basic boilerplate) or a static binding (e.g in the typescript-basic boilerplate).