本文將展示如何使用 Prisma來操作我們的資料庫。
首先,我們通過Docker來創建一個PostgreSQL資料庫
///// apps\iron-ecommerce-server\docker-compose.yml
version: "3"
services:
pg:
image: postgres
restart: always
environment:
POSTGRES_USER: dbuser
POSTGRES_PASSWORD: dbpass
volumes:
- ./.db:/var/lib/postgresql/data
ports:
- "5432:5432"
adminer:
image: adminer
restart: always
environment:
ADMINER_DEFAULT_SERVER: pg
ports:
- "8080:8080"
depends_on:
- pg
///// bash
> docker-compose up -d
並且這裡推薦一個vscode extension,SQLTools
以及SQLTools PostgreSQL/Cockroach Driver
。可以用來查看我們db,我們安裝後也把他加入到workspace的recomment中。
///// .vscode\extensions.json
{
"recommendations": [
"nrwl.angular-console",
"esbenp.prettier-vscode",
"firsttris.vscode-jest-runner",
"ms-playwright.playwright",
"dbaeumer.vscode-eslint",
"editorconfig.editorconfig",
"ms-edgedevtools.vscode-edge-devtools",
"mtxr.sqltools",
"mtxr.sqltools-driver-pg"
]
}
接下來我們要安裝prisma並進行設置
pnpm add -D prisma
pnpm add @prisma/client nestjs-prisma
創建prisma schema,並且我們postgresql url格式如下postgresql://<your_username>:<your_password>@localhost:5432/<your_database>
。
首先我們創建環境設置在根目錄下,並加入ignore
///// .env
# POSTGRES
POSTGRES_USER=dbuser
POSTGRES_PASSWORD=dbpass
POSTGRES_DB=iron-ecommerce
# Nest run locally
DB_HOST=localhost
# Nest run in docker, change host to database container name
# DB_HOST=postgres
DB_PORT=5432
DB_SCHEMA=iron-ecommerce-test
# Prisma database connection
DATABASE_URL=postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${DB_HOST}:${DB_PORT}/${POSTGRES_DB}?schema=${DB_SCHEMA}&sslmode=prefer
///// .gitignore
//...
# Next.js
.next
.env
**/.db
///// apps\iron-ecommerce-server\prisma\schema.prisma
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model Product {
id String @id @default(cuid())
name String
price Float
description String
imageUrl String
}
在apps\iron-ecommerce-server\project.json
中,我們新增了多個與 Prisma 相關的指令,例如 prisma-generate、prisma-db-push 和 prisma-seed等指令以方便操作
//....
},
"prisma": {
"executor": "nx:run-commands",
"options": {
"command": "prisma"
}
},
"prisma-generate": {
"executor": "nx:run-commands",
"options": {
"command": "prisma generate --schema=apps/iron-ecommerce-server/prisma/schema.prisma"
}
},
"prisma-db-push": {
"executor": "nx:run-commands",
"options": {
"command": "prisma db push --schema=apps/iron-ecommerce-server/prisma/schema.prisma"
}
},
"prisma-seed": {
"executor": "nx:run-commands",
"options": {
"command": "prisma db seed"
}
}
},
"tags": []
}
1.執行pnpm exec nx run iron-ecommerce-server:prisma-generate
來生成我們的schema,並且genarator會在.\node_modules\.pnpm\@prisma+client@5.4.1_prisma@5.4.1\node_modules\@prisma\client
生成
2.接下來我們初始化創建我們的db,執行 pnpm exec nx run iron-ecommerce-server:prisma-db-push
。Db push
打開.vscode\settings.json
來設定我們的SQLTools
{
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true,
"source.organizeImports": true
},
"vscode-edge-devtools.webhint": false,
"eslint.validate": ["json"],
"sqltools.connections": [
{
"previewLimit": 50,
"server": "localhost",
"port": 5432,
"askForPassword": true,
"driver": "PostgreSQL",
"name": "pg",
"database": "iron-ecommerce",
"username": "dbuser"
}
]
}
接下來我們使用SQLTools開啟,並連線到db,密碼我們目前設置dbpass
打開後我們能看到我們的Products
3.接下來我們創建一個seed方法在我們的資料庫塞資料:
///// apps\iron-ecommerce-server\prisma\seed.ts
import { faker } from "@faker-js/faker";
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
async function main() {
await prisma.product.deleteMany();
console.log("Seeding...");
const productCount = 50;
for (let i = 0; i < productCount; i++) {
const productData = {
name: faker.commerce.productName(),
price: parseFloat(faker.commerce.price()),
description: faker.commerce.productDescription(),
imageUrl: faker.image.url()
};
await prisma.product.create({
data: productData
});
}
console.log("Seeding completed");
}
main()
.catch((e) => console.error(e))
.finally(async () => {
await prisma.$disconnect();
});
設定prisma seed環境,打開package.json
並加入prisma
"config": {
"commitizen": {
"path": "cz-git"
}
},
"prisma": {
"seed": "ts-node apps/iron-ecommerce-server/prisma/seed.ts"
}
}
接著,我們執行指令產生seeds
pnpm exec nx run iron-ecommerce-server:prisma-seed
我們回到SQLTools來看一下是否生成資料再db裡了。
我們能看到,我們的db裡已經有資料了。
本文我們介紹了如何利用Docker快速創建PostgreSQL資料庫,並通過Prisma等指令進行操作。並且使用SQLTools來查看資料庫。最後我們使用Prisma的seed功能創建fake data。下一篇文章我們將修改我們service,在service中使用prisma來操作db