0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

TypeORM の data-source.ts 設定

Last updated at Posted at 2025-02-01

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 で遊べる。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?