Prisma、Express、TypeScript、PostgreSQL を使用した RESTful API の構築

WBOY
リリース: 2024-09-07 06:31:32
オリジナル
791 人が閲覧しました

Building a RESTful API with Prisma, Express, TypeScript, and PostgreSQL

目次

  1. はじめに

    • Prisma、Express、TypeScript、PostgreSQL の概要
    • なぜ Prisma を ORM として使用するのですか?
    • 環境のセットアップ
  2. プロジェクトの初期セットアップ

    • 新しい Node.js プロジェクトのセットアップ
    • TypeScript の構成
    • 必要なパッケージのインストール
  3. PostgreSQL のセットアップ

    • PostgreSQL のインストール
    • 新しいデータベースの作成
    • 環境変数の構成
  4. Prisma のセットアップ

    • Prisma のインストール
    • プロジェクトで Prisma を初期化しています
    • Prisma スキーマの構成
  5. データモデルの定義

    • Prisma スキーマ言語 (PSL) を理解する
    • API のモデルの作成
    • Prisma による移行
  6. Prisma と Express の統合

    • Express サーバーのセットアップ
    • Prisma を使用した CRUD オペレーションの作成
    • エラー処理と検証
  7. タイプ セーフティのための TypeScript の使用

    • Prisma を使用した型の定義
    • タイプセーフなクエリとミューテーション
    • API 開発における TypeScript の活用
  8. API のテスト

    • Prisma モデルの単体テストの作成
    • Supertest と Jest による統合テスト
    • Prisma を使用してデータベースをモックする
  9. 導入に関する考慮事項

    • 実稼働用の API の準備
    • PostgreSQL のデプロイ
    • Node.js アプリケーションのデプロイ
  10. 結論

    • 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 プロジェクトのセットアップ

  1. 新しいプロジェクト ディレクトリを作成します:
   mkdir prisma-express-api
   cd prisma-express-api
ログイン後にコピー
  1. 新しい Node.js プロジェクトを初期化します:
   npm init -y
ログイン後にコピー

これにより、プロジェクト ディレクトリに package.json ファイルが作成されます。

TypeScript の構成

  1. TypeScript および Node.js タイプをインストールします:
   npm install typescript @types/node --save-dev
ログイン後にコピー
  1. プロジェクトで TypeScript を初期化します:
   npx tsc --init
ログイン後にコピー

このコマンドは、TypeScript の構成ファイルである tsconfig.json ファイルを作成します。プロジェクトの必要に応じて変更します。基本的な設定は次のとおりです:

   {
     "compilerOptions": {
       "target": "ES2020",
       "module": "commonjs",
       "strict": true,
       "esModuleInterop": true,
       "skipLibCheck": true,
       "forceConsistentCasingInFileNames": true,
       "outDir": "./dist"
     },
     "include": ["src/**/*"]
   }
ログイン後にコピー
  1. プロジェクト構造を作成します:
   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 and with your PostgreSQL username and password. This connection string will be used by Prisma to connect to your PostgreSQL database.


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 サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!