検索
ホームページウェブフロントエンドjsチュートリアルPrisma、Express、TypeScript、PostgreSQL を使用した RESTful API の構築

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"
</password></user>

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

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
ブラウザを超えて:現実世界のJavaScriptブラウザを超えて:現実世界のJavaScriptApr 12, 2025 am 12:06 AM

現実世界におけるJavaScriptのアプリケーションには、サーバー側のプログラミング、モバイルアプリケーション開発、モノのインターネット制御が含まれます。 2。モバイルアプリケーションの開発は、ReactNativeを通じて実行され、クロスプラットフォームの展開をサポートします。 3.ハードウェアの相互作用に適したJohnny-Fiveライブラリを介したIoTデバイス制御に使用されます。

next.jsを使用してマルチテナントSaaSアプリケーションを構築する(バックエンド統合)next.jsを使用してマルチテナントSaaSアプリケーションを構築する(バックエンド統合)Apr 11, 2025 am 08:23 AM

私はあなたの日常的な技術ツールを使用して機能的なマルチテナントSaaSアプリケーション(EDTECHアプリ)を作成しましたが、あなたは同じことをすることができます。 まず、マルチテナントSaaSアプリケーションとは何ですか? マルチテナントSaaSアプリケーションを使用すると、Singの複数の顧客にサービスを提供できます

next.jsを使用してマルチテナントSaaSアプリケーションを構築する方法(フロントエンド統合)next.jsを使用してマルチテナントSaaSアプリケーションを構築する方法(フロントエンド統合)Apr 11, 2025 am 08:22 AM

この記事では、許可によって保護されたバックエンドとのフロントエンド統合を示し、next.jsを使用して機能的なedtech SaaSアプリケーションを構築します。 FrontEndはユーザーのアクセス許可を取得してUIの可視性を制御し、APIリクエストがロールベースに付着することを保証します

JavaScript:Web言語の汎用性の調査JavaScript:Web言語の汎用性の調査Apr 11, 2025 am 12:01 AM

JavaScriptは、現代のWeb開発のコア言語であり、その多様性と柔軟性に広く使用されています。 1)フロントエンド開発:DOM操作と最新のフレームワーク(React、Vue.JS、Angularなど)を通じて、動的なWebページとシングルページアプリケーションを構築します。 2)サーバー側の開発:node.jsは、非ブロッキングI/Oモデルを使用して、高い並行性とリアルタイムアプリケーションを処理します。 3)モバイルおよびデスクトップアプリケーション開発:クロスプラットフォーム開発は、反応および電子を通じて実現され、開発効率を向上させます。

JavaScriptの進化:現在の傾向と将来の見通しJavaScriptの進化:現在の傾向と将来の見通しApr 10, 2025 am 09:33 AM

JavaScriptの最新トレンドには、TypeScriptの台頭、最新のフレームワークとライブラリの人気、WebAssemblyの適用が含まれます。将来の見通しは、より強力なタイプシステム、サーバー側のJavaScriptの開発、人工知能と機械学習の拡大、およびIoTおよびEDGEコンピューティングの可能性をカバーしています。

javascriptの分解:それが何をするのか、なぜそれが重要なのかjavascriptの分解:それが何をするのか、なぜそれが重要なのかApr 09, 2025 am 12:07 AM

JavaScriptは現代のWeb開発の基礎であり、その主な機能には、イベント駆動型のプログラミング、動的コンテンツ生成、非同期プログラミングが含まれます。 1)イベント駆動型プログラミングにより、Webページはユーザー操作に応じて動的に変更できます。 2)動的コンテンツ生成により、条件に応じてページコンテンツを調整できます。 3)非同期プログラミングにより、ユーザーインターフェイスがブロックされないようにします。 JavaScriptは、Webインタラクション、シングルページアプリケーション、サーバー側の開発で広く使用されており、ユーザーエクスペリエンスとクロスプラットフォーム開発の柔軟性を大幅に改善しています。

pythonまたはjavascriptの方がいいですか?pythonまたはjavascriptの方がいいですか?Apr 06, 2025 am 12:14 AM

Pythonはデータサイエンスや機械学習により適していますが、JavaScriptはフロントエンドとフルスタックの開発により適しています。 1. Pythonは、簡潔な構文とリッチライブラリエコシステムで知られており、データ分析とWeb開発に適しています。 2。JavaScriptは、フロントエンド開発の中核です。 node.jsはサーバー側のプログラミングをサポートしており、フルスタック開発に適しています。

JavaScriptをインストールするにはどうすればよいですか?JavaScriptをインストールするにはどうすればよいですか?Apr 05, 2025 am 12:16 AM

JavaScriptは、最新のブラウザにすでに組み込まれているため、インストールを必要としません。開始するには、テキストエディターとブラウザのみが必要です。 1)ブラウザ環境では、タグを介してHTMLファイルを埋め込んで実行します。 2)node.js環境では、node.jsをダウンロードしてインストールした後、コマンドラインを介してJavaScriptファイルを実行します。

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。

SublimeText3 Linux 新バージョン

SublimeText3 Linux 新バージョン

SublimeText3 Linux 最新バージョン

DVWA

DVWA

Damn Vulnerable Web App (DVWA) は、非常に脆弱な PHP/MySQL Web アプリケーションです。その主な目的は、セキュリティ専門家が法的環境でスキルとツールをテストするのに役立ち、Web 開発者が Web アプリケーションを保護するプロセスをより深く理解できるようにし、教師/生徒が教室環境で Web アプリケーションを教え/学習できるようにすることです。安全。 DVWA の目標は、シンプルでわかりやすいインターフェイスを通じて、さまざまな難易度で最も一般的な Web 脆弱性のいくつかを実践することです。このソフトウェアは、

AtomエディタMac版ダウンロード

AtomエディタMac版ダウンロード

最も人気のあるオープンソースエディター

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser は、オンライン試験を安全に受験するための安全なブラウザ環境です。このソフトウェアは、あらゆるコンピュータを安全なワークステーションに変えます。あらゆるユーティリティへのアクセスを制御し、学生が無許可のリソースを使用するのを防ぎます。