Prismaとは
- データベースを簡単に扱うことができる
- 次世代オープンソースORMです。
ORM(Object Relational Mapping)
- メソッドベースでDBをいじることができる(create(),update(),delete())
- SQL文知らなくてもRDB触れるよ
Object
=人間(体重、身長、食事、色々な情報を持っている)、下記のことをひっくるめてObjectと呼ぶ
method=
食べる、歩く
property
=身長、体重
Relational
=関係性がある
Mapping
=割り当てる、何かと何かと割り当てる、地図を作るときにMappingするみたいな


VScodeで作成
$ npm init -y
※package.json(初期化、作成)
$ npm i prisma express nodemon @prisma/client
※モジュール郡のインストール
※express = node.jsのフレームワーク
※nodemon = ローカルサーバーを再起動しやすくするもの
※client = データ挿入、削除するため使用するモジュール
node.jsインストール方法
### server.js作成
-------------------------------------
const express = require("express");
const app = express();
const PORT = 8000;
app.listen(PORT, () => {
console.log("サーバーが起動中・・・")
});
-------------------------------------
$ npm start
※サーバー起動
$ npx prisma init
- データベース作成していく
CREATE DATABASE smapledb;
¥c sampledb
### .env
-------------------------------------
# Environment variables declared in this file are automatically made available to Prisma.
# See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema
# Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.
# See the documentation for all the connection string options: https://pris.ly/d/connection-strings
DATABASE_URL="postgresql://postgres(意味なし):パスワード@localhost:5432/smpledb(作成したテーブル)?schema=public"
-------------------------------------
### schema.prisema
-------------------------------------
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model Posts {
id Int @default(autoincrement()) @id
title String
boby String
}
※autoincreament=記事を投稿するたびに1,2,3,4連番としてIDを指定する
-------------------------------------
$ npx prisma migrate dev --name init
※マイグレーション実行
$ npx prisma studio
※prismaが立ち上がる

APIの作成
- Postomanでインストール
const { PrismaCliant } = require("@prisma/client");
const express = require("express");
const app = express();
const PORT = 8000;
const prisma = new PrismaCliant();
app.use(express.json());
※json形式で送るとエラーが発生するので上記内容を記載
app.post("/", async (req, res) => {
const { title, boby } = req.boby;
const posts = await prisma.posts.create({
data: {
title: title,
boby: boby,
},
});
return res.json(posts);
});
app.listen(PORT, () => {
console.log("サーバーが起動中・・・")
});