Prismaとは?
次世代オープンソースのORM(Object Relational Mapping)になります。DBを操作のためのライブラリでサーバー上で実装します。
構築
サーバーインストール
1 |
npm install prisma --save-dev |
クライアントインストール
1 |
npm install @prisma/client |
初期化
1 |
npx prisma init |
以下の二つが自動で生成されています。
- prismaというディレクトリ
- .envファイル
実装
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
generator client { provider = "prisma-client-js" } datasource db { provider = "sqlite" url = "file:./dev.db" } model Link { id Int @id @default(autoincrement()) create_at DateTime @default(now()) description String url String } |
datasource dbのurl
init時は環境変数に定義されているURLを使うようになっているのですが、SQliteのパスに書き換えます。
また、Linkというモデルを定義しています。
マイグレートする。
マイグレートとは、モデルをもとにSQliteに適用させる操作になります。
1 |
npx prisma migrate dev(自分で名前を決めれます。) |
Enter a name for the new migration
コメントを入れることができます。最初のコミットであれば、initとでも入力しておけば良いでしょう。
prismaディレクトリ配下に以下の階層が自動生成されます。
1 2 3 |
migrations/ └─ 20221010014543_init/ └─ migration.sql |
中身は以下でSQL文が自動生成されています。
1 2 3 4 5 6 |
CREATE TABLE "Link" ( "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "create_at" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, "description" TEXT NOT NULL, "url" TEXT NOT NULL );な |
なお、モデルに新しくフィールドを追加するなどと行った場合は毎回マイグレーションのコマンドを実行する必要があります。
Prismaクライアントを生成する。
1 |
npx prisma generate |
登録
1 2 3 4 5 6 7 8 9 |
const { PrismaClient } = require("@prisma/client"); const prisma = new PrismaClient(); await prisma.link.create({ data: { description: "xxx", url: "yyy", }, }); |
検索
1 2 3 4 |
const { PrismaClient } = require("@prisma/client"); const prisma = new PrismaClient(); const allLinks = await prisma.link.findMany(); |
データベースを閉じる
prismaとのやりとりはasync/awaitで非同期で行うことになるので、try〜catch〜finally句のfinally句にでも記述しておくと良いでしょう。
1 |
prisma.$disconnect; |
Apollo Serverと連携
1 2 3 4 5 6 7 8 9 10 11 12 |
const { PrismaClient } = require("@prisma/client"); const prisma = new PrismaClient(); const server = new ApolloServer({ typeDefs: fs.readFileSync(path.join(__dirname, "schema.graphql"), "utf-8"), resolvers, context: { prisma, }, csrfPrevention: true, cache: "bounded", }); |
context
「どこでも使えますよ」という意味になります。要はQueryでもMutationなどのリゾルバ関数内でどこでもprismaという変数が使えますよというニュアンスになります。
Query
1 2 3 4 5 6 |
Query: { info: () => "リターンinfo", feed: async (parent, args, context) => { return context.prisma.link.findMany(); }, }, |
Mutation
1 2 3 4 5 6 7 8 9 10 11 |
Mutation: { post: (parent, args, context) => { const newLink = context.prisma.link.create({ data: { description: args.description, url: args.url, }, }); return newLink; }, }, |
Prismaスタジオ
データベースの中身をビジュアル的に見ることができるツールです。
1 |
npx prisma studio |
データの閲覧だけでなく、削除などもできます。
この記事へのコメントはありません。