GraphQL integrate with Prisma
2021-09-16
0. Prisma Intro
Prisma 是一个 db tool,提供 interact with db 的 API。
包含:
- Prisma Client: An auto-generated and type-safe query builder for Node.js & TypeScript.
- Prisma Migrate (experimental): A declarative data modeling & migration system.
- Prisma Studio (experimental): A GUI to view and edit data in your database.
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
Prisma
npm install prisma --save-dev
npm install @prisma/client
npx prisma init
schema.prisma
- Data source: Specifies your database connection.
- Generator: Indicates that you want to generate Prisma Client.
- Data model: Defines your application models. Each model will be mapped to a table in the underlying database.
SQLite
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.
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
Maintenance
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
- update prisma schema
- update graphql resolver (install auth related package and pass userId in context)
- refactoring the resolver functions
- Create user and put the bearer token to http header to test.
mutation {
signup(name: "Alice", email: "[email protected]", password: "graphql") {
token
user {
id
}
}
}
Details can be referred from this awesome post