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?

Nest.js その3 AppDataSource

Posted at

AppDataSource

import { DataSource } from 'typeorm';
import { UsersEntity } from '../entities/users.entity';
import { TodosEntity } from 'src/entities/todos.entity';
import { NewsEntity } from 'src/entities/news.entity';

export const AppDataSource = new DataSource({
  type: 'mysql',
  host: 'localhost',
  port: 3306,
  username: 'test',
  password: 'test',
  database: 'test',
  synchronize: true,
  entities: [UsersEntity,TodosEntity,NewsEntity],
});





TypeORM を使ってデータベース接続を設定するコード

TypeORMとは
JavaScript/TypeScriptのクラスを使って、データベースを操作できる仕組みのこと。

export const AppDataSource = new DataSource




TypeORMでデータベース接続の設定を作るための構文

new DataSource




type: データベースの種類
host: 接続先
port: 通信に使う番号 MySQLは通常[3306]
username: データベースログインに使う情報
password: データベースログインに使う情報
database: 接続するデータベースの名前
synchronize:  true にすると、TypeORMが自動でテーブルを作ってくれる
(いちいち SQL書かなくてもよい、開発環境のみで使用→本番環境で実行時に既存のテーブルを勝手に変更・削除される可能性がある,予期しないデータ消失が起こる可能性がある)

entities: どのクラスをテーブルとして使うかをTypeORMに教えるリスト

type: 'mysql',
  host: 'localhost',
  port: 3306,
  username: 'test',
  password: 'test',
  database: 'test',
  synchronize: true,
  entities: [UsersEntity,TodosEntity,NewsEntity],
});




docker-compose.yml
docker-compose.yml ファイルで、MySQL コンテナを立ち上げるための設定


services:mysql  mysql というサービス名でデータベースコンテナを立ち上げる定義
image      ベースになるDockerイメージ
container_name コンテナ名
volumes     データの永続化→自分のPCの./mysql-data フォルダを
        コンテナ内のMySQL のデータフォルダ /var/lib/mysql にくっつける
        Dockerのコンテナは削除すると中のデータも消えるのが基本

ports:- 3306:3306 自分のPCの3306番に来たアクセスをMySQLコンテナの3306番とつなぐ

MySQL の初期設定  Docker Compose で MySQL の初期設定を自動化するための環境変数(environment:) のセット
environment:
MYSQL_ROOT_PASSWORD: test 管理者ユーザーのパスワード
MYSQL_DATABASE: test    自動で作ってくれるデータベース名
MYSQL_USER: test       ユーザーの名前
MYSQL_PASSWORD: test     ユーザーのパスワード

version: '3.8'

services:
  mysql:
    image: mysql:8.0
    container_name: mysql
    volumes:
      - ./mysql-data:/var/lib/mysql
    ports:
      - 3306:3306
    environment:
      MYSQL_ROOT_PASSWORD: test
      MYSQL_DATABASE: test
      MYSQL_USER: test
      MYSQL_PASSWORD: test
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?