TypeORM がうまくいかないなら prisma でもいいか、と思ったけどプレーンなオブジェクトを扱えないっぽいので TypeORM に戻ってきた。
https://qiita.com/okadabasso/items/2bc2ed4bd1405179f263 ではディレクトリ指定ができずに諦めたのだが、最近 github copilot を入れて色々調べていたらヒントが見つかった。
現在のバージョンでの設定
import { DataSource } from 'typeorm';
import { join } from 'path';
export const AppDataSource = new DataSource({
type: 'postgres', // or your preferred database type
host: 'pg',
port: 5432,
username: 'testuser',
password: 'password',
database: 'testdb',
synchronize: false,
logging: true,
logger: 'advanced-console',
entities: [
join(__dirname, 'entities/**/*.{ts,js}'),
], // Add your entities here
migrations: [
join(__dirname, 'data/migrations/**/*.{ts,js}'),
],
subscribers: [],
});
AppDataSource.initialize()
.then(() => {
console.log('Data Source has been initialized!');
})
.catch((err) => {
console.error('Error during Data Source initialization:', err);
});
entities に join(__dirname, 'entities/**/*.ts')
と join(__dirname, 'entities/**/*.js')
を並べているのは前者が migration の変更検出用、後者が実行時のエンティティ検出用。前者がないとmigration:generate が機能せず、後者がないと実行時にエンティティクラスが検出できない。
これで心置きなく TypeORM で遊べる。