目錄
-
簡介
- Prisma、Express、TypeScript 和 PostgreSQL 概述
- 為什麼 Prisma 作為 ORM?
- 設定環境
-
初始項目設定
- 設定新的 Node.js 專案
- 配置 TypeScript
- 安裝所需的軟體包
-
設定 PostgreSQL
- 安裝 PostgreSQL
- 建立新資料庫
- 配置環境變數
-
設定 Prisma
- 安裝 Prisma
- 在專案中初始化 Prisma
- 配置 Prisma 架構
-
定義資料模型
- 了解 Prisma 架構語言 (PSL)
- 為 API 建立模型
- 使用 Prisma 進行遷移
-
將 Prisma 與 Express 整合
- 設定 Express 伺服器
- 使用 Prisma 建立 CRUD 操作
- 錯誤處理與驗證
-
使用 TypeScript 實作型別安全性
- 使用 Prisma 定義型別
- 類型安全的查詢與突變
- 在 API 開發中利用 TypeScript
-
測試 API
- 為 Prisma 模型編寫單元檢定
- 使用 Supertest 和 Jest 進行整合測試
- 使用 Prisma 模擬資料庫
-
部署注意事項
- 為生產準備 API
- 部署 PostgreSQL
- 部署 Node.js 應用程式
-
結論
- 將 Prisma 與 Express 和 TypeScript 結合使用的好處
- 最終想法與後續步驟
一、簡介
Prisma、Express、TypeScript 和 PostgreSQL 概述
在現代 Web 開發中,建立健壯、可擴展且類型安全的 API 至關重要。結合 Prisma 作為 ORM、Express 用於伺服器端邏輯、TypeScript 用於靜態類型以及 PostgreSQL 作為可靠的資料庫解決方案的強大功能,我們可以創建強大的 RESTful API。
Prisma 透過提供支援類型安全性查詢、遷移和無縫資料庫模式管理的現代 ORM 來簡化資料庫管理。 Express 是一個最小且靈活的 Node.js Web 應用程式框架,為 Web 和行動應用程式提供了一組強大的功能。 TypeScript 為 JavaScript 添加了靜態類型定義,有助於在開發過程的早期捕獲錯誤。 PostgreSQL 是一個功能強大的開源關係型資料庫系統,以其可靠性和功能集而聞名。
為什麼 Prisma 作為 ORM?
Prisma 與 Sequelize 和 TypeORM 等傳統 ORM 相比具有多種優點:
- 類型安全的資料庫查詢:自動產生的類型確保您的資料庫查詢是類型安全且無錯誤的。
- 自動遷移: Prisma 提供強大的遷移系統,讓您的資料庫架構與 Prisma 架構保持同步。
- 直覺的資料建模: Prisma 架構檔案(以 PSL 編寫)易於理解和維護。
- 廣泛的生態系統: Prisma 與其他工具和服務無縫集成,包括 GraphQL、REST API 和 PostgreSQL 等流行資料庫。
設定環境
在我們深入研究程式碼之前,請確保您的電腦上安裝了以下工具:
- Node.js(推薦LTS版本)
- npm 或 Yarn(用於套件管理)
- TypeScript(用於靜態型別)
- PostgreSQL(作為我們的資料庫)
安裝這些工具後,我們就可以開始建立我們的 API。
2. 初始項目設定
設定新的 Node.js 項目
- 建立一個新的專案目錄:
mkdir prisma-express-api cd prisma-express-api
- 初始化一個新的 Node.js 專案:
npm init -y
這將在您的專案目錄中建立一個 package.json 檔案。
配置 TypeScript
- 安裝 TypeScript 和 Node.js 類型:
npm install typescript @types/node --save-dev
- 在專案中初始化 TypeScript:
npx tsc --init
此指令建立一個 tsconfig.json 文件,它是 TypeScript 的設定檔。根據您的項目需要對其進行修改。這是基本設定:
{ "compilerOptions": { "target": "ES2020", "module": "commonjs", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "outDir": "./dist" }, "include": ["src/**/*"] }
- 建立專案結構:
mkdir src touch src/index.ts
安裝所需的套件
要開始使用 Express 和 Prisma,您需要安裝一些必要的軟體包:
npm install express prisma @prisma/client npm install --save-dev ts-node nodemon @types/express
- express: The web framework for Node.js.
- prisma: The Prisma CLI for database management.
- @prisma/client: The Prisma client for querying the database.
- ts-node: Runs TypeScript directly without the need for precompilation.
- nodemon: Automatically restarts the server on file changes.
- @types/express: TypeScript definitions for Express.
3. Setting Up PostgreSQL
Installing PostgreSQL
PostgreSQL can be installed via your operating system’s package manager or directly from the official website. For example, on macOS, you can use Homebrew:
brew install postgresql brew services start postgresql
Creating a New Database
Once PostgreSQL is installed and running, you can create a new database for your project:
psql postgres CREATE DATABASE prisma_express;
Replace prisma_express with your preferred database name.
Configuring Environment Variables
To connect to the PostgreSQL database, create a .env file in your project’s root directory and add the following environment variables:
DATABASE_URL="postgresql://<user>:<password>@localhost:5432/prisma_express" </password></user>
Replace
4. Setting Up Prisma
Installing Prisma
Prisma is already installed in the previous step, so the next step is to initialize it within the project:
npx prisma init
This command will create a prisma directory containing a schema.prisma file and a .env file. The .env file should already contain the DATABASE_URL you specified earlier.
Configuring the Prisma Schema
The schema.prisma file is where you'll define your data models, which will be used to generate database tables.
Here’s a basic example schema:
generator client { provider = "prisma-client-js" } datasource db { provider = "postgresql" url = env("DATABASE_URL") } model User { id Int @id @default(autoincrement()) name String email String @unique createdAt DateTime @default(now()) posts Post[] } model Post { id Int @id @default(autoincrement()) title String content String? published Boolean @default(false) authorId Int author User @relation(fields: [authorId], references: [id]) }
In this schema, we have two models: User and Post. Each model corresponds to a database table. Prisma uses these models to generate type-safe queries for our database.
5. Defining the Data Model
Understanding Prisma Schema Language (PSL)
Prisma Schema Language (PSL) is used to define your database schema. It's intuitive and easy to read, with a focus on simplicity. Each model in the schema represents a table in your database, and each field corresponds to a column.
Creating Models for the API
In the schema defined earlier, we created two models:
- User: Represents users in our application.
- Post: Represents posts created by users.
Migrations with Prisma
To apply your schema changes to the database, you’ll need to run a migration:
npx prisma migrate dev --name init
This command will create a new migration file and apply it to your database, creating the necessary tables.
6. Integrating Prisma with Express
Setting Up the Express Server
In your src/index.ts, set up the basic Express server:
import express, { Request, Response } from 'express'; import { PrismaClient } from '@prisma/client'; const app = express(); const prisma = new PrismaClient(); app.use(express.json()); app.get('/', (req: Request, res: Response) => { res.send('Hello, Prisma with Express!'); }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); });
This code sets up a simple Express server and initializes the Prisma client.
Creating CRUD Operations with Prisma
Next, let’s create some CRUD (Create, Read, Update, Delete) routes for our User model.
Create a new user:
app.post('/user', async (req: Request, res: Response) => { const { name, email } = req.body; const user = await prisma.user.create({ data: { name, email }, }); res.json(user); });
Read all users:
app.get('/users', async (req: Request, res: Response) => { const users = await prisma.user.findMany(); res.json(users); });
Update a user:
app.put('/user/:id', async (req: Request, res: Response) => { const { id } = req.params; const { name, email } = req.body; const user = await prisma.user.update({ where: { id: Number(id) }, data: { name, email }, }); res.json(user); });
Delete a user:
app.delete('/user/:id', async (req: Request, res: Response) => { const { id } = req.params; const user = await prisma.user.delete({ where: { id: Number(id) }, }); res.json(user); });
Error Handling and Validation
To enhance the robustness of your API, consider adding error handling and validation:
app.post('/user', async (req: Request, res: Response) => { try { const { name, email } = req.body; if (!name || !email) { return res.status(400).json({ error: 'Name and email are required' }); } const user = await prisma.user.create({ data: { name, email }, }); res.json(user); } catch (error) { res.status(500).json({ error: 'Internal Server Error' }); } });
7. Using TypeScript for Type Safety
Defining Types with Prisma
Prisma automatically generates TypeScript types for your models based on your schema. This ensures that your database queries are type-safe.
For example, when creating a new user, TypeScript will enforce the shape of the data being passed:
const user = await prisma.user.create({ data: { name, email }, // TypeScript ensures 'name' and 'email' are strings. });
Type-Safe Queries and Mutations
With TypeScript, you get autocomplete and type-checking for all Prisma queries, reducing the chance of runtime errors:
const users: User[] = await prisma.user.findMany();
Leveraging TypeScript in API Development
Using TypeScript throughout your API development helps catch potential bugs early, improves code readability, and enhances overall development experience.
8. Testing the API
Writing Unit Tests for Prisma Models
Testing is an essential part of any application development. You can write unit tests for your Prisma models using a testing framework like Jest:
npm install jest ts-jest @types/jest --save-dev
Create a jest.config.js file:
module.exports = { preset: 'ts-jest', testEnvironment: 'node', };
Example test for creating a user:
import { PrismaClient } from '@prisma/client'; const prisma = new PrismaClient(); test('should create a new user', async () => { const user = await prisma.user.create({ data: { name: 'John Doe', email: 'john.doe@example.com', }, }); expect(user).toHaveProperty('id'); expect(user.name).toBe('John Doe'); });
Integration Testing with Supertest and Jest
You can also write integration tests using Supertest:
npm install supertest --save-dev
Example integration test:
import request from 'supertest'; import app from './app'; // Your Express app test('GET /users should return a list of users', async () => { const response = await request(app).get('/users'); expect(response.status).toBe(200); expect(response.body).toBeInstanceOf(Array); });
Mocking the Database with Prisma
For testing purposes, you might want to mock the Prisma client. You can do this using tools like jest.mock() or by creating a mock instance of the Prisma client.
9. Deployment Considerations
Preparing the API for Production
Before deploying your API, ensure you:
- Remove all development dependencies.
- Set up environment variables correctly.
- Optimize the build process using tools like tsc and webpack.
Deploying PostgreSQL
You can deploy PostgreSQL using cloud services like AWS RDS, Heroku, or DigitalOcean. Make sure to secure your database with proper authentication and network settings.
Deploying the Node.js Application
For deploying the Node.js application, consider using services like:
- Heroku: For simple, straightforward deployments.
- AWS Elastic Beanstalk: For more control over the infrastructure.
- Docker: To containerize the application and deploy it on any cloud platform.
10. Conclusion
Benefits of Using Prisma with Express and TypeScript
Using Prisma as an ORM with Express and TypeScript provides a powerful combination for building scalable, type-safe, and efficient RESTful APIs. With Prisma, you get automated migrations, type-safe queries, and an intuitive schema language, making database management straightforward and reliable.
Congratulations!! You've now built a robust RESTful API using Prisma, Express, TypeScript, and PostgreSQL. From setting up the environment to deploying the application, this guide covered the essential steps to get you started. As next steps, consider exploring advanced Prisma features like nested queries, transactions, and more complex data models.
Happy coding!
以上是使用 Prisma、Express、TypeScript 和 PostgreSQL 來建立 RESTful API的詳細內容。更多資訊請關注PHP中文網其他相關文章!

我使用您的日常技術工具構建了功能性的多租戶SaaS應用程序(一個Edtech應用程序),您可以做同樣的事情。 首先,什麼是多租戶SaaS應用程序? 多租戶SaaS應用程序可讓您從唱歌中為多個客戶提供服務

本文展示了與許可證確保的後端的前端集成,並使用Next.js構建功能性Edtech SaaS應用程序。 前端獲取用戶權限以控制UI的可見性並確保API要求遵守角色庫

JavaScript是現代Web開發的核心語言,因其多樣性和靈活性而廣泛應用。 1)前端開發:通過DOM操作和現代框架(如React、Vue.js、Angular)構建動態網頁和單頁面應用。 2)服務器端開發:Node.js利用非阻塞I/O模型處理高並發和實時應用。 3)移動和桌面應用開發:通過ReactNative和Electron實現跨平台開發,提高開發效率。

JavaScript的最新趨勢包括TypeScript的崛起、現代框架和庫的流行以及WebAssembly的應用。未來前景涵蓋更強大的類型系統、服務器端JavaScript的發展、人工智能和機器學習的擴展以及物聯網和邊緣計算的潛力。

JavaScript是現代Web開發的基石,它的主要功能包括事件驅動編程、動態內容生成和異步編程。 1)事件驅動編程允許網頁根據用戶操作動態變化。 2)動態內容生成使得頁面內容可以根據條件調整。 3)異步編程確保用戶界面不被阻塞。 JavaScript廣泛應用於網頁交互、單頁面應用和服務器端開發,極大地提升了用戶體驗和跨平台開發的靈活性。

Python更适合数据科学和机器学习,JavaScript更适合前端和全栈开发。1.Python以简洁语法和丰富库生态著称,适用于数据分析和Web开发。2.JavaScript是前端开发核心,Node.js支持服务器端编程,适用于全栈开发。

JavaScript不需要安裝,因為它已內置於現代瀏覽器中。你只需文本編輯器和瀏覽器即可開始使用。 1)在瀏覽器環境中,通過標籤嵌入HTML文件中運行。 2)在Node.js環境中,下載並安裝Node.js後,通過命令行運行JavaScript文件。

如何在Quartz中提前發送任務通知在使用Quartz定時器進行任務調度時,任務的執行時間是由cron表達式設定的。現�...


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

SublimeText3漢化版
中文版,非常好用

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。