目次
はじめに
プロジェクトの初期セットアップ
PostgreSQL のセットアップ
Prisma のセットアップ
データモデルの定義
Prisma と Express の統合
タイプ セーフティのための TypeScript の使用
API のテスト
導入に関する考慮事項
結論
現代の Web 開発では、堅牢でスケーラブルでタイプセーフな API を構築することが重要です。 ORM としての Prisma、サーバー側ロジックとしての Express、静的型付けのための TypeScript、および信頼性の高いデータベース ソリューションとしての PostgreSQL の機能を組み合わせることで、強力な RESTful API を作成できます。
Prisma は、タイプセーフなクエリ、移行、シームレスなデータベース スキーマ管理をサポートする最新の ORM を提供することにより、データベース管理を簡素化します。 Express は、Web およびモバイル アプリケーションに堅牢な機能セットを提供する、最小限で柔軟な Node.js Web アプリケーション フレームワークです。 TypeScript は静的型定義を JavaScript に追加し、開発プロセスの早い段階でエラーを検出するのに役立ちます。 PostgreSQL は、その信頼性と機能セットで知られる強力なオープンソース リレーショナル データベース システムです。
Prisma には、Sequelize や TypeORM などの従来の ORM に比べていくつかの利点があります。
コードを詳しく説明する前に、次のツールがマシンにインストールされていることを確認してください。
これらのツールをインストールしたら、API の構築を開始できます。
mkdir prisma-express-api cd prisma-express-api
npm init -y
これにより、プロジェクト ディレクトリに package.json ファイルが作成されます。
npm install typescript @types/node --save-dev
npx tsc --init
このコマンドは、TypeScript の構成ファイルである tsconfig.json ファイルを作成します。プロジェクトの必要に応じて変更します。基本的な設定は次のとおりです:
{ "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
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
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.
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"
Replace
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.
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.
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.
In the schema defined earlier, we created two models:
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.
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.
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); });
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' }); } });
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. });
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();
Using TypeScript throughout your API development helps catch potential bugs early, improves code readability, and enhances overall development experience.
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'); });
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); });
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.
Before deploying your API, ensure you:
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.
For deploying the Node.js application, consider using services like:
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 中国語 Web サイトの他の関連記事を参照してください。