[항해99] 51일차 prisma. 프리즈마 npm
항해 99
51일차:
어제에 이어서 프리즈마 공부를했다.
아침 9시부터 앉아서 저녁 11시38분까지 시간이 너무빨리갔다.
생각보다 직접 코딩하는 시간은 2시간도 안된것같은데... 오늘 뭘한건지 ?? 모르겠다.
데일리 리포트 라도 다시 써야하는걸까 ...
https://www.youtube.com/watch?v=pkT1-BUP_lo&t=499s
게시판 기획에 거의 2-3시간을 쓴거같은데... 이것때문이였나..?
ERD그리는데도 한두어 시간 쓴것같고....
어쩃든 생각보다 프로그래밍 을 한시간이없어서찝찝한 하루인것같다.
그래서 프리즈마 install & getting started 라도 제대로 이해하고 이해한것을 설명해야겠다.
+ 자기전에 그분이 사람들의 글을 읽으면 그사람이 뭔생각을 하는지 알수있다고 하셧다.
내글을 찬찬히 읽어보면... 다른사람이 내글을 읽고 내가 뭔생각을 하고있는지 알수있을까 의문이든다.
너무 의식의 흐름대로 쓰는걸까?
작년 블로그를 시작할때 글쓰기 연습도할겸 시작하게 되었는데, 확실히 글쓰기 도 많이써봐야 실력이 좋아지는것같다.
중학교 수준에 멈춘 내 한국어 글쓰기도 점점 좋아지는것같다.
1)ERD
Ultimate Entity Relationship Diagram Tutorial (ER Diagrams)
DB설계할때 정말 중요한부분인것같다. 옛날에 수업에서 배울때는데 대충 숙제하라니깐 배워놓고 숙제하고 다까먹었는데
이런 조각 조각들을 프로젝트를 직접해보면서 퍼즐을 맞추는느낌이든다.
학교에 돈을 그렇게 들이고 이퍼즐을 맞추는건 항해에와서 한다니? 원래 이런거를 학교에서도 배운것들을 퍼즐을 맞춰서 practical 한것을 배우는게 학교가 해줘야하는 역할이 아닌가...
https://www.guru99.com/er-diagram-tutorial-dbms.html
ER Diagram: Entity Relationship Diagram Model | DBMS Example
Details Last Updated: 14 July 2021 What is ER Diagram? ER Diagram stands for Entity Relationship Diagram, also known as ERD is a diagram that displays the relationship of entity sets stored in a database. In other words, ER diagrams help to explain the log
www.guru99.com
프리즈마 :
prisma , sequlizer 모두 ORM 라이브러리.
prsima를 사용했을때 skema를 짜는 게 굉장히 짧아진다.
sequlizer했을때는 워낙 어떻게 돌아가는지 몰라서 오래걸린것도 있지만 model을 짜는데 시간이 많이들었던것을 기억한다.
이번 파이널 프로젝트는 , 먼저 ERD를 먼저 그려놓고, prisma skema 를 작성했다.
프리즈마를 쓰는 이유중에 제일 큰 이유가 skema가 굉장히 깔끔하게 나온다는것이다.
공식문서 자체가설명이 잘되어있다. 라고하는데 나는 잘 못느끼겟다. 쓰다보니깐 또 잘되어있는것같기도하고...
내눈엔 그놈이 그놈인것같다. 조금더 자세히 설명이되어있다? (다른 offical doc보다) 정도 인것같다.
Getting started에서 차근 차근 따라가면 된다.
https://www.prisma.io/docs/getting-started/quickstart/
Quickstart: Getting started with TypeScript & SQLite
Get started with Prisma in 5 minutes. You will learn how to send queries to a SQLite database in a plain TypeScript script using Prisma Client.
www.prisma.io
처음화면에 이렇게 나온다.
- Prisma Client: Auto-generated and type-safe query builder for Node.js & TypeScript
- Prisma Migrate: Migration tool to easily evolve your database schema from prototyping to production
- Prisma Studio: GUI to view and edit data in your database
Client는 우리가 api 를 짤수있는것 - sequlizer에서 model을 가져오는 부분이 없고 그냥 저걸 통째로 가져올수있는것같다.
가져오려면 먼저 schema 를 만들고 migrate 을 해야한다.
Migrate schema를 짠것을 migratoin file로 변환해준다? (db로넣어준다?)
Studio database GUI를 열수있다. 힘들게 workbench안가도 여기서 확인가능.
1. prsima installation :
npm install prisma
npx prisma init
npx prisma init 을 하면 .env 파일 이아래처럼 나온다.
file에 Database url을 설정해준다.
mysql or postgresql
PORT = 8080
# This was inserted by `prisma init`:
# Environment variables declared in this file are automatically made available to Prisma.
# See the documentation for more detail: https://pris.ly/d/prisma-schema#using-environment-variables
# Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server (Preview) and MongoDB (Preview).
# See the documentation for all the connection string options: https://pris.ly/d/connection-strings
DATABASE_URL="mysql://{mysql account} :{password};'@localhost:3306/{dbname}"
그리고나서 prisma/schema.prisma
위에서 db 설정을 해줘야한다.
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
}
그럼 db에 연결 할수있다.
2. db schema짜기
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
}
model User {
id Int @id //@id => primary key
name String @unique // unique
email String? // ? => optional
password String
comment Comment[] // user have many comments
post Post[] // user have many posts
}
model Post {
postId Int @id @default(autoincrement())
createdAt DateTime @default(now())
content String
user User @relation(fields:[userid],references:[id]) // foreign key
userid Int // foreign key. (field : is the foreign key and reference is the where the key from)
comment Comment[]
}
model Comment {
commentId Int @id @default(autoincrement())
createdAt DateTime @default(now())
content String
user User @relation(fields:[userId],references:[id])// foreign key
userId Int
post Post @relation(fields:[postId],references:[postId]) foreign key
postId Int
}
특히 관계설정할때
foreign key설정할때 양쪽에서 해줘야하는데,
user model 에서도 post[] 로 설정하고 post model에서도 @relation 으로 설정해주면된다.
User {
post Post[]
}
Post{
user User @relation(fields:[userId],references:[id])
nickId String
}
프리즈마에서 관계설정(association )은 sequelizer와 다르게
그냥 @relateion(field: {foriengkey }, reference: { entity} 형식으로 예를들면
comment와 user를 이어준다고했을때 아래처럼 스케마를 짜면된다.
model User {
id Int @id @default(autoincrement())
email String @unique
nickname String @unique
password String
comments Comment[]
}
model Comment {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
content String
user User @relation(fields:[userId],references:[id])
userId Int @default(0)
}
schema 를 다짜고나서
npx prisma migrate dev
npx prisma migrate dev 를 하면 처음에는 migration file이름을 설정하라고 물어본다.
이후로 schema를 업데이트할때마다 migrate를해야하는데 이름은 따로 다시 설정하지않는다.
완료되면 generated Prisma Client가 뜬다.
npx generate을 하면
npx prisma generate
이화면이 뜬다. 그럼 Prsima client를 쓸수있다는말인것같다.
그러면 인제부터다시 app.js나 app.ts로 돌아가서 api를 짜면된다.
migration 에 관한 정확하고 자세한 설명은 공식문서
Using Prisma Migrate
Create database tables with Prisma Migrate
www.prisma.io
schema 파일이 잘 설정되어서 migrate되엇는지 확인하려면 , prisma studio 를 열어서 확인할수있다.
npx prisma studio
그럼 웹브라우저에서 GUI로 확인가능.
자 이제부터그럼 client에다가 api 를 짜면된다
import express, { Request, Response } from 'express'
import cors from 'cors'
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
const app = express()
const PORT = 3000
app.use(cors({ credentials: true }))
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
// user
app.get('/users', async (req: Request, res: Response) => {
const email: string = "test@test.com"
const nickname : string= "potatoking"
const password : string= "potatoxiro"
const newUser = await prisma.user.create({
data: {
email,nickname,password,
}
})
res.json(newUser)
})
PrismaClinet를 통째로 import를해오고 사용할수있다.
'IT > Bootcamp 항해99' 카테고리의 다른 글
[ 항해99] 54일차 OOP , MVC pattern (4) | 2021.07.31 |
---|---|
[항해99] 52일차 github (0) | 2021.07.29 |
[항해99] 49일차 & 50일차 prisma , test code , typescript (2) | 2021.07.27 |
[항해99] 48일차 파이널 프로젝트 (2) | 2021.07.25 |
[항해99] 47일차 혼돈의 카오스의 날 (1) | 2021.07.23 |