概要
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();