TypeORMでプロジェクトを下記コマンドで作成する
typeorm init --name MyProject --database mysql
src/index.ts にサンプルファイルが出力される
import "reflect-metadata";
import {createConnection} from "typeorm";
import {User} from "./entity/User";
createConnection().then(async connection => {
console.log("Inserting a new user into the database...");
const user = new User();
user.firstName = "Timber";
user.lastName = "Saw";
user.age = 25;
await connection.manager.save(user);
console.log("Saved a new user with id: " + user.id);
console.log("Loading users from the database...");
const users = await connection.manager.find(User);
console.log("Loaded users: ", users);
console.log("Here you can setup and run express/koa/any other framework.");
}).catch(error => console.log(error));
これを下記で実行するとコンソールが処理が終了せずに固まる
ts-node src/index.ts
Inserting a new user into the database...
Saved a new user with id: 3
Loading users from the database...
Loaded users: [
User { id: 1, firstName: 'Timber', lastName: 'Saw', age: 25 }
]
Here you can setup and run express/koa/any other framework.
<ここでフリーズする=処理が抜けない>
mysql> show processlist;で確認すると<ここでフリーズする>の箇所ではコネクションは活きている状態になっている。
typeormを使ってCLIツールなど使うときこれだと困るので、一つの解決策は process.exit()を差し込めばいいがさすがにそれは最終手段なのでコネクションをクローズすることで処理が抜けるようになった。
import "reflect-metadata";
import {createConnection} from "typeorm";
import {User} from "./entity/User";
createConnection().then(async connection => {
const users = await connection.manager.find(User)
console.log("Loaded users: ", users)
await connection.close() // ここを追加
}).catch(error => console.log(error));
TypeORMのサンプルは明示的にcloseの記載はないので、明示的に終了したいときはcloseをいれるのが良さそう。