Prisma、Express、TypeScript、PostgreSQL を使用した RESTful API の構築
目次
-
はじめに
- 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 アプリケーションのデプロイ
-
結論
- Express および TypeScript で Prisma を使用する利点
- 最終的な考えと次のステップ
1. はじめに
Prisma、Express、TypeScript、PostgreSQL の概要
現代の Web 開発では、堅牢でスケーラブルでタイプセーフな API を構築することが重要です。 ORM としての Prisma、サーバー側ロジックとしての Express、静的型付けのための TypeScript、および信頼性の高いデータベース ソリューションとしての PostgreSQL の機能を組み合わせることで、強力な RESTful API を作成できます。
Prisma は、タイプセーフなクエリ、移行、シームレスなデータベース スキーマ管理をサポートする最新の ORM を提供することにより、データベース管理を簡素化します。 Express は、Web およびモバイル アプリケーションに堅牢な機能セットを提供する、最小限で柔軟な Node.js 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
このコマンドは、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
- 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"
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 中国語 Web サイトの他の関連記事を参照してください。

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック











Pythonは、スムーズな学習曲線と簡潔な構文を備えた初心者により適しています。 JavaScriptは、急な学習曲線と柔軟な構文を備えたフロントエンド開発に適しています。 1。Python構文は直感的で、データサイエンスやバックエンド開発に適しています。 2。JavaScriptは柔軟で、フロントエンドおよびサーバー側のプログラミングで広く使用されています。

Web開発におけるJavaScriptの主な用途には、クライアントの相互作用、フォーム検証、非同期通信が含まれます。 1)DOM操作による動的なコンテンツの更新とユーザーインタラクション。 2)ユーザーエクスペリエンスを改善するためにデータを提出する前に、クライアントの検証が実行されます。 3)サーバーとのリフレッシュレス通信は、AJAXテクノロジーを通じて達成されます。

現実世界でのJavaScriptのアプリケーションには、フロントエンドとバックエンドの開発が含まれます。 1)DOM操作とイベント処理を含むTODOリストアプリケーションを構築して、フロントエンドアプリケーションを表示します。 2)node.jsを介してRestfulapiを構築し、バックエンドアプリケーションをデモンストレーションします。

JavaScriptエンジンが内部的にどのように機能するかを理解することは、開発者にとってより効率的なコードの作成とパフォーマンスのボトルネックと最適化戦略の理解に役立つためです。 1)エンジンのワークフローには、3つの段階が含まれます。解析、コンパイル、実行。 2)実行プロセス中、エンジンはインラインキャッシュや非表示クラスなどの動的最適化を実行します。 3)ベストプラクティスには、グローバル変数の避け、ループの最適化、constとletsの使用、閉鎖の過度の使用の回避が含まれます。

開発環境におけるPythonとJavaScriptの両方の選択が重要です。 1)Pythonの開発環境には、Pycharm、Jupyternotebook、Anacondaが含まれます。これらは、データサイエンスと迅速なプロトタイピングに適しています。 2)JavaScriptの開発環境には、フロントエンドおよびバックエンド開発に適したnode.js、vscode、およびwebpackが含まれます。プロジェクトのニーズに応じて適切なツールを選択すると、開発効率とプロジェクトの成功率が向上する可能性があります。

CとCは、主に通訳者とJITコンパイラを実装するために使用されるJavaScriptエンジンで重要な役割を果たします。 1)cは、JavaScriptソースコードを解析し、抽象的な構文ツリーを生成するために使用されます。 2)Cは、Bytecodeの生成と実行を担当します。 3)Cは、JITコンパイラを実装し、実行時にホットスポットコードを最適化およびコンパイルし、JavaScriptの実行効率を大幅に改善します。

Pythonはデータサイエンスと自動化により適していますが、JavaScriptはフロントエンドとフルスタックの開発により適しています。 1. Pythonは、データ処理とモデリングのためにNumpyやPandasなどのライブラリを使用して、データサイエンスと機械学習でうまく機能します。 2。Pythonは、自動化とスクリプトにおいて簡潔で効率的です。 3. JavaScriptはフロントエンド開発に不可欠であり、動的なWebページと単一ページアプリケーションの構築に使用されます。 4. JavaScriptは、node.jsを通じてバックエンド開発において役割を果たし、フルスタック開発をサポートします。

JavaScriptは、Webサイト、モバイルアプリケーション、デスクトップアプリケーション、サーバー側のプログラミングで広く使用されています。 1)Webサイト開発では、JavaScriptはHTMLおよびCSSと一緒にDOMを運用して、JQueryやReactなどのフレームワークをサポートします。 2)ReactNativeおよびIonicを通じて、JavaScriptはクロスプラットフォームモバイルアプリケーションを開発するために使用されます。 3)電子フレームワークにより、JavaScriptはデスクトップアプリケーションを構築できます。 4)node.jsを使用すると、JavaScriptがサーバー側で実行され、高い並行リクエストをサポートします。
