Luna Tech

Tutorials For Dummies.

GraphQL integrate with Prisma


0. Prisma Intro


Prisma 是一个 db tool,提供 interact with db 的 API。


Why Prisma?

real-world resolver 会很复杂很难写; real-world 需要考虑 auth, pagination, filtering, realtime 等等事情。

Prisma does the heavy-lifting for devs.

In the GraphQL API, Prisma helps us to migrate our database schema.

1. Setup


npm install prisma --save-dev
npm install @prisma/client

npx prisma init



SQLite does not have a separate server process. SQLite reads and writes directly to ordinary disk files. A complete SQL database with multiple tables, indices, triggers, and views, is contained in a single disk file.

Install sqlite tutorial

Run migration

Since we already have the schema in schema.prisma, we can use the following command in the root of the project to create db migration (i.e., map schema to db tables).

The migration will generate sql command.

npx prisma migrate dev

Generating Prisma Client (based on the data model)

This command will generate client in node modules and we can use it in the code.

npx prisma generate


Note: After every change you make to the data model, you need to migrate your database and then re-generate Prisma Client.

npx prisma migrate dev --name "add-user-model"
npx prisma generate

2. Use Prisma Client to interact with db

After adding a script to use Prisma Client and query the db, we can run this file to get the query result.

node src/script.js

3. Connect GraphQL Sever and SQLite db

We are going to use Prisma Client to build the connection, it acts as an interface to the db.

3.1 Wire up GraphQL server with Prisma Client

You can write to the context when the GraphQL server itself is being initiated.

We can attach an instance of Prisma Client (in another article) to the context when initiating the server and then access it from inside our resolvers via the context argument.

Prisma Client exposes a CRUD API for the models in your datamodel for you to read and write in your database. These methods are auto-generated based on your model definitions in schema.prisma

3.2 Prisma Studio

A GUI to view the data.

npx prisma studio

4. Authentication

  1. update prisma schema
  2. update graphql resolver (install auth related package and pass userId in context)
  3. refactoring the resolver functions
  4. Create user and put the bearer token to http header to test.
mutation {
  signup(name: "Alice", email: "[email protected]", password: "graphql") {
    user {

Details can be referred from this awesome post