Rhyztech blog

TypeORMのv0.2からv0.3での大きな変更とか

tech

TypeORMのv0.2からv0.3で大きく変わった部分やいくつかのメソッドがdeprecatedされているので主要なものを紹介したいと思います。 今回紹介するのは次の3つ。

  1. DBへのコネクションの接続にDataSourceクラスの追加
  2. findOneメソッドの引数と返却値の変更
  3. find*系のメソッドの引数の形式の変更

全ての変更を追いたい場合はRelease 0.3.0をみると良いです。

DBへのコネクションの接続方法の変更

v0.3でのアップデートでインパクトの大きい変更が、DBへのコネクションの接続方法の変更です。
v0.2まではcreateConnectionによってConnectionのインスタンスを生成してDBの接続を管理していましたが、 v0.3からはDataSourceクラスによってDBの接続を管理します。
この変更によってcreateConnectionConnectionは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" }
    },
});

Copyright 2024, rhyztech. All Rights Reserved.