LoginSignup
8
5

More than 5 years have passed since last update.

TypeScript用ORMapper「typeorm」を試してみる

Last updated at Posted at 2017-12-12

概要

typeormはTypeScriptで記述できるORMapperライブラリ。
mysql, postgresql, mongodbなど主要なRDBMSやNoSqlをサポートしてる。
mongoとmysqlを使ってみたのでその記録。

Githubリポジトリ

設定

ormconfig.json (拡張子は色々と変更できる)にて、各データベースの設定を記述する。connectionを作成する際、引数を指定する事により指定データベース情報を取得できる。
※ ormconfig.json内の#はコメントアウトだと思ってください

ormconfig.json
# 複数指定する場合は配列で定義する。entities配下を検索するため、その中にEntityが存在しないとエラーになる。
{
  "name": "default",
  "type": "mysql",
  "host": "localhost",
  "port": 3306,
  "username": "test",
  "password": "test",
  "database": "test",
  "synchronize": true, # このパラメータをtrueにするとAlter Tableが走る...。
  "logging": false,
  "entities": [
    "src/entity/*.js"
  ],
  "subscribers": [
    "src/subscriber/*.js"
  ],
  "migrations": [
    "src/migration/*.js"
  ],
  "cli": {
    "entitiesDir": "src/entity",
    "migrationsDir": "src/migration",
    "subscribersDir": "src/subscriber"
  }
}

mongodb編

mongodbを使用するにはnpm install mongodb --save
公式リポジトリにあるsampleを見るとわかるが、mongodbのEntity作成方法はmysqlなどとは異なるので注意。

mongo-sample.ts
import "reflect-metadata";
import {createConnection} from "typeorm";

createConnection().then(async connection => {
    const channel: TChannel = new TChannel();
    channel.channelId = "1111";
    channel.name = "世界部屋";
    channel.description = "全体チャット";
    channel.ownerId = "";
    channel.isDismiss = false;
    channel.maxMember = 10000;

    await connection.mongoManager.save(channel);
});

mysql編

mysqlを使用するには、npm install mysql --saveでmysql-driverをインストールする必要がある。
ormconfig.json"synchronize": true,を設定するとEntityに設定したデコレーターと同期してしまう模様。AlterTableが勝手に走ってしまったので注意。

sample.ts
import "reflect-metadata";
import {Column, createConnection, getConnectionOptions, PrimaryGeneratedColumn, Entity} from "typeorm";

@Entity()
export class Users {
    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

    @Column({
        unique: true,
    })
    email: string;

    @Column()
    password: string;

    @Column()
    remember_token: string;

    @Column()
    created_at: string;

    @Column()
    updated_at: string;
}

async function testConnect() {
    const option = await getConnectionOptions('rdbms');
    const dbCon = await createConnection(option);
    const res = await dbCon.getRepository(Users).findOne({id: 1});
    console.log(res); // Users {id: 1,name: 'oh',email: 'taylor@example.com', password: ''}
}

testConnect();
8
5
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
8
5