• Stars
    star
    476
  • Rank 92,280 (Top 2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created almost 7 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

GraphQL Binding for Prisma 1 (using GraphQL schema delegation)

prisma-binding

npm version

⚠️ A note about this repository

prisma-binding is a dedicated graphql-binding for Prisma 1 (based on GraphQL schema delegation). Note that Prisma 2.0 doesn't support Prisma binding.

Unless you explicitly want to use Prisma 1 and schema delegation we recommend that you use Nexus for building GraphQL servers!

Overview

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.

Here is how it works:

  1. Create your Prisma service by defining data model
  2. Download generated database schema definition 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

Install

yarn add prisma-binding
# or
npm install --save prisma-binding

Example

Consider the following data model for your Prisma service:

type User {
  id: ID! @unique
  name: String
}

If you instantiate Prisma based on this service, you'll be able to send the following queries/mutations:

const {Prisma} = require('prisma-binding')

// Instantiate `Prisma` based on concrete service
const prisma = new Prisma({
  typeDefs: 'schemas/database.graphql',
  endpoint: 'https://us1.prisma.sh/demo/my-service/dev',
  secret: 'my-super-secret-secret'
})

// Retrieve `name` of a specific user
prisma.query.user({ where: { id: 'abc' } }, '{ name }')

// Retrieve `id` and `name` of all users
prisma.query.users(null, '{ id name }')

// Create new user called `Sarah` and retrieve the `id`
prisma.mutation.createUser({ data: { name: 'Sarah' } }, '{ id }')

// Update name of a specific user and retrieve the `id`
prisma.mutation.updateUser({ where: { id: 'abc' }, data: { name: 'Sarah' } }, '{ id }')

// Delete a specific user and retrieve the `id`
prisma.mutation.deleteUser({ where: { id: 'abc' } }, '{ id }')

Under the hood, each of these function calls is simply translated into an actual HTTP request against your Prisma service (using graphql-request).

The API also allows to ask whether a specific node exists in your Prisma database:

// Ask whether a post exists with `id` equal to `abc` and whose
// `author` is called `Sarah` (return boolean value)
prisma.exists.Post({
  id: 'abc',
  author: {
    name: 'Sarah'
  }
})

API

constructor(options: PrismaOptions): Prisma

The PrismaOptions type has the following fields:

Key Required Type Default Note
typeDefs Yes string - Type definition string or file path to the schema definition of your Prisma service (typically a file called database.graphql or prisma.graphql)
endpoint Yes string - The endpoint of your Prisma service
secret Yes string - The secret of your Prisma service
fragmentReplacements No FragmentReplacements null A list of GraphQL fragment definitions, specifying fields that are required for the resolver to function correctly
debug No boolean false Log all queries/mutations to the console

query and mutation

query and mutation are public properties on your Prisma instance. They both are of type Query and expose a number of auto-generated delegate resolver functions that are named after the fields on the Query and Mutation types in your Prisma database schema.

Each of these delegate resolvers in essence provides a convenience API for sending queries/mutations to your Prisma service, so you don't have to spell out the full query/mutation from scratch and worry about sending it over HTTP. This is all handled by the delegate resolver function under the hood.

Delegate resolver have the following interface:

(args: any, info: GraphQLResolveInfo | string): Promise<T>

The input arguments are used as follows:

  • args: An object carrying potential arguments for the query/mutation
  • info: An object representing the selection set of the query/mutation, either expressed directly as a string or in the form of GraphQLResolveInfo (you can find more info about the GraphQLResolveInfo type here)

The generic type T corresponds to the type of the respective field.

exists

exists also is a public property on your Prisma instance. Similar to query and mutation, it also exposes a number of auto-generated functions. However, it exposes only a single function per type. This function is named according to the root field that allows the retrieval of a single node of that type (e.g. User for a type called User). It takes a where object as an input argument and returns a boolean value indicating whether the condition expressed with where is met.

This function enables you to easily check whether a node of a specific type exists in your Prisma database.

request

The request method lets you send GraphQL queries/mutations to your Prisma service. The functionality is identical to the auto-generated delegate resolves, but the API is more verbose as you need to spell out the full query/mutation. request uses graphql-request under the hood.

Here is an example of how it can be used:

const query = `
  query ($userId: ID!){
    user(id: $userId) {
      id
      name
    }
  }
`

const variables = { userId: 'abc' }

prisma.request(query, variables)
  .then(result => console.log(result))
// sample result:
// {"data": { "user": { "id": "abc", "name": "Sarah" } } }

forwardTo

If you just want to forward a query to the exact same underlying prisma query, you can use forwardTo:

const {forwardTo} = require('prisma-binding')

const resolvers = {
  Query: {
    posts: forwardTo('db')
  }
}

const server = new GraphQLServer({
  typeDefs: './src/schema.graphql',
  resolvers,
  context: req => ({
    ...req,
    db: new Prisma({
      typeDefs: 'src/generated/prisma.graphql',
      endpoint: '...',
      secret: 'mysecret123',
    }),
    debug: true,
  }),
})

server.start(
  () => console.log(`Server is running on http://localhost:4000`),
)

Prisma

More Repositories

1

graphqlgen

βš™οΈ Generate type-safe resolvers based upon your GraphQL Schema
TypeScript
818
star
2

graphql-prisma-typescript

🏑 GraphQL server reference implementation (Airbnb clone) in Typescript using Prisma & graphql-yoga
TypeScript
749
star
3

graphql-framework-experiment

Code-First Type-Safe GraphQL Framework
TypeScript
673
star
4

get-graphql-schema

Fetch and print the GraphQL schema from a GraphQL HTTP endpoint. (Can be used for Relay Modern.)
TypeScript
665
star
5

yoga2

A lightweight 'Ruby on Rails'-like framework for GraphQL
TypeScript
347
star
6

python-graphql-client

Simple GraphQL client for Python 2.7+
Python
156
star
7

dripip

Opinionated CLI for continuous delivery of npm packages
TypeScript
100
star
8

konn

TypeScript
89
star
9

graphql-import-loader

Webpack loader for `graphql-import`
TypeScript
83
star
10

http-link-dataloader

πŸ“šπŸ“‘ HTTP Apollo Link with batching & caching provided by dataloader.
TypeScript
77
star
11

bema

🐎 Delightful benchmarking for Node.js
TypeScript
73
star
12

graphql-framework-experiment-examples

Runnable examples to help you learn how to use Nexus.
TypeScript
64
star
13

nextjs-graphql-api-examples

Next.js example GraphQL API implementations
TypeScript
38
star
14

next-prisma-plugin

TypeScript
19
star
15

graphqlday.org

JavaScript
12
star
16

oss.prisma.io

Documentation content for oss.prisma.io (GraphQL Playground, GraphQL Yoga, GraphQL Config...)
10
star
17

vscode-next

TypeScript
6
star
18

graphql-config-extension-prisma

TypeScript
6
star
19

mockapie

TypeScript
1
star
20

renovate-config

Standard Renovate configurations for Labs team projects.
1
star
21

team

πŸ‘©β€πŸ”¬πŸ‘¨β€πŸ”¬Past sprint demo recordings & more
1
star
22

prettier-config

Standard Prettier configuration for Labs team projects.
1
star