TypeORMのv0.2からv0.3での大きな変更とか
TypeORMのv0.2からv0.3で大きく変わった部分やいくつかのメソッドがdeprecatedされているので主要なものを紹介したいと思います。 今回紹介するのは次の3つ。
- DBへのコネクションの接続に
DataSource
クラスの追加 findOne
メソッドの引数と返却値の変更find*
系のメソッドの引数の形式の変更
全ての変更を追いたい場合はRelease 0.3.0をみると良いです。
DBへのコネクションの接続方法の変更
v0.3でのアップデートでインパクトの大きい変更が、DBへのコネクションの接続方法の変更です。
v0.2まではcreateConnection
によってConnection
のインスタンスを生成してDBの接続を管理していましたが、
v0.3からはDataSource
クラスによってDBの接続を管理します。
この変更によってcreateConnection
やConnection
はdeprecatedになっています。
v0.2
const config = await getConnectionOptions();
const connection: Connection = await createConnection({
...config
});
v0.3
const dataSource = new DataSource({
type: "mysql",
// some config
});
await dataSource.initialize();
またこれによってTypeDIとの連携をしていたtypeorm-typedi-extensionsがうまく機能しなくなります。
TypeDIと連携したい場合はDataSource
クラスのインスタンスをDIコンテナで渡せば良さそうです。
const dataSource = new DataSource({
// some config
});
await dataSource.initialize();
Container.set(DataSource, dataSource);
// some repository
const dataSource = Container.get(DataSource);
const repository = dataSource.getRepository(User);
findOne
メソッドの引数と返却値の変更
v0.3でのアップデートで、もう1つインパクトの大きい変更がfindOne
の変更です。
v0.2ではfindOne
メソッドは第1引数でプライマリキーを、第2引数でオプションを指定していましたが、
v0.3ではFindOptionsWhere
型の引数にまとめられており、プライマリキーはwhere句で指定するようになりました。
また、値がなかった場合の返却値はundefined
からnull
に変更されています。
v0.2
const repository = getRepository(User);
const user: User | undefined = await repository.findOne(id, { relations: ["photo"] });
v0.3
const repository = dataSource.getRepository(User);
const user: User | null = await repository.findOne({ where: { id: id }, relations: { photo: true } });
find*
系のメソッドの引数の形式の変更
find*
系のメソッドのオプションの指定方法が大きく変わりました。
v0.2でselectやrelationsの指定は文字列で行なっていましたが、v0.3ではオブジェクトでの指定に統一されました。
また、これによってrelations先のカラムの指定やソートが行えるようになりました。
v0.2
const users = await repository.find({
select: ["firstName", "lastName"]
where: {
{ firstName: "john", lastName: "jeo" },
},
relations: ["project"],
order: {
id: "DESC",
firstName: "ASC",
},
});
v0.3
const users = await repository.find({
select: {
id: true,
firstName: true,
lastName: true,
project: {
id: true,
name: true,
importance: true,
}
}
where: {
project: { name: "TypeORM", initials: "TORM" },
},
relations: { project: true }
order: {
id: "DESC",
project: { importance: "ASC" }
},
});