0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[nodejs] Prismaで始めるデータベース管理

Posted at

はじめに

この記事では、TypeScriptとPrismaを組み合わせて使用する方法と、その組み合わせがNode.jsアプリケーションのデータベース管理をどのように改善するかを説明します。

TypeScriptの型安全性とPrismaの強力なデータモデリング機能を利用することで、開発プロセスが効率化され、エラーが減少します。

必要な環境

  1. Node.jsがインストールされた開発環境
  2. TypeScriptの基本的な知識
  3. 使用するデータベースシステムへのアクセス(例: PostgreSQL, MySQL)

プロジェクトのセットアップ

①プロジェクトのフォルダを作成する

mkdir my-prisma-ts-app

プロジェクトのフォルダに移動する

cd my-prisma-ts-app

package.jsonなどを初期化する

npm init -y

②typescriptのセットアップ

下記の記事をご参照ください。

③Prismaのセットアップ

Prismaのインストール

npm install prisma --save-dev
npm install @prisma/client

Prismaの初期設定

npx prisma init

データベーススキーマの設計

schema.prismaにモデルを定義し、データベースとの同期を行います。ユーザーモデルの例:

model User {
  id    Int     @id @default(autoincrement())
  name  String
  email String  @unique
}

データベースとの同期

Prisma Migrateを使用してデータベーススキーマを更新:

npx prisma migrate dev --name init

アプリケーションへの統合

TypeScriptでPrismaクライアントを使用してデータベース操作を行う例:

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

async function main() {
  const newUser = await prisma.user.create({
    data: {
      name: 'Alice',
      email: 'alice@example.com'
    }
  });
  console.log('Created new user:', newUser);
}

main()
  .catch(e => {
    throw e;
  })
  .finally(async () => {
    await prisma.$disconnect();
  });

まとめ

TypeScriptとPrismaの組み合わせにより、Node.jsアプリケーションのデータベース管理がより安全で効率的になります。このセットアップは、開発プロセスを加速させ、エラーのリスクを最小化するため、特に大規模なアプリケーション開発において非常に有効です

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?