Built Twitter Like App - 8

Install Prisma

1
npm install -D prisma

Init Prisma

1
npx prisma init

Modify DB Config

Modify file prisma/schema.prisma

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

// Looking for ways to speed up your queries, or scale easily with your serverless or edge functions?
// Try Prisma Accelerate: https://pris.ly/cli/accelerate-init

generator client {
provider = "prisma-client-js"
}

datasource db {
provider = "mysql"
url = env("DATABASE_URL")
}

model User{
id Int @id @default(autoincrement())
name String?
username String? @unique
bio String?
email String? @unique
emailVerified DateTime?
image String?
coverImage String?
profileImage String?
hashedPassword String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
followingIds FollowingId[]
hasNotification Boolean?

posts Post[]
comments Comment[]
notifications Notification[]
}

model FollowingId {
id Int @id @default(autoincrement())
followingId Int
user User @relation(fields: [followingId], references: [id], onDelete: Cascade)
}

model Post {
id Int @id @default(autoincrement())
body String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
userId Int
likedIds Int

user User @relation(fields: [userId], references: [id], onDelete: Cascade)

comments Comment[]
}

model Comment {
id Int @id @default(autoincrement())
body String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
userId Int
postId Int

user User @relation(fields: [userId], references: [id], onDelete: Cascade)
post Post @relation(fields: [postId], references: [id], onDelete: Cascade)
}

model Notification {
id Int @id @default(autoincrement())
body String
userId Int
createdAt DateTime @default(now())

user User @relation(fields: [userId], references: [id], onDelete: Cascade)
}

Modify file .env

1
DATABASE_URL="mysql:/<user>:<password>@192.168.50.188:3501/TWDB"

Push DB model

Shell command:

1
npx prisma db push

可以看到以下执行结果:

1
2
3
4
5
6
7
8
9
Applying the following changes:

[+] Collection `User`
[+] Collection `Post`
[+] Collection `Comment`
[+] Collection `Notification`
[+] Unique index `User_username_key` on ({"username":1})

🚀 Your database indexes are now in sync with your Prisma schema. Done in 144ms

Install Prisma Client

1
npm install @prisma/client

Add DB Code

Add file libs/prismadb.ts

1
2
3
4
5
6
7
8
9
10
11
import { PrismaClient  } from "@prisma/client";

declare global {
var prisma: PrismaClient | undefined
}

const client = globalThis.prisma || new PrismaClient()

if ( process.env.NODE_ENV !== 'production') globalThis.prisma = client;

export default client;

请我喝杯咖啡吧~

支付宝
微信