postgresql 在turborepo中配置typeorm来创建表

vql8enpb  于 2023-05-17  发布在  PostgreSQL
关注(0)|答案(1)|浏览(118)

我想用turborepo和postgresql建立一个项目。
到目前为止我做了什么:创建一个简单的nestjs + typeorm运行得很好,表是在postgres-db中创建的。所以一切都很好。
其中最重要的部分是postgres连接选项:

type: 'postgres',
    host: 'localhost',
    port: 5432,
    username: 'dbuser',
    password: 'dbuserpw',
    database: 'db_test',
    entities: ['dist/src/**/*.entity.js'],
    synchronize: true,
    logging: 'all',

现在我想在workspace中使用turborepo,但是typorm现在似乎不能正常工作,因为它安装在projectfolder中,而projectfolder不再是nestjs项目文件夹。nestjs项目文件夹是孔项目的子文件夹。
我已经尝试了很多不同的方法来为实体给予正确的路径,但它们不再在postgres中创建。是否需要任何配置来启用typeorm以访问子项目中的实体?

k5hmc34c

k5hmc34c1#

张贴文件的所有内容会减少问题的概述。
同时,我找到了一个可行的解决方案。在大多数教程中,数据库的使用是在app.module.ts中按以下方式完成的:

import { Module } from '@nestjs/common';
import config from './typeorm.config';

@Module({
  imports: [
    TypeOrm.forRoot(config),  // <-- this is not forcing the table initialisation when used with turborepo
  ],
  controllers: [AppController],
  providers: [AppService],
})

解决方案是创建一个连接,并在一个单独的模块中同步数据库,如下图所示(Database.ts):

import { PostgresConnectionOptions } from 
  'typeorm/driver/postgres/PostgresConnectionOptions';
import config from './typeorm.config';
import { Connection, createConnection } from 'typeorm';
import { Injectable } from '@nestjs/common';

@Injectable()
export class Database {
  public Connection: Connection;
  public Configuration: PostgresConnectionOptions;
  public Environment: string;

  constructor() {
    this.Environment = process.env.NODE_ENV;
    this.Configuration = config;

    console.log('Detecting ' + this.Environment + ' environment.');
    console.log(
      'DB information host: ' +
        this.Configuration.host +
        '; user: ' +
        this.Configuration.username,
    );

    this.createConnection();
  }

  private createConnection() {
    createConnection(this.Configuration)
     .then((connection) => {
       console.log('connected!');
        this.Connection = connection;
        connection.synchronize();  // <-- here we create the tables
     })
     .catch((error) => {
        console.log('Error: ' + error);
      });
  }
}

要使数据库在project中可访问,请在main. ts的bootstrap函数中定义它:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './Api/App/app.module';
import { Database } from './Database';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  app.get(Database);
  await app.listen(3000);
}

相关问题