是否可以像这里一样使用连接类provide
?
import { Connection, createConnection } from 'typeorm';
export const databaseProviders = [{
provide: Connection,
useFactory: async () => await createConnection({
type: 'postgres',
host: 'localhost',
port: 5432,
username: 'postgres',
password: 'postgres',
database: 'testo',
entities: [
__dirname + '/../**/*.entity{.ts,.js}',
],
logging: true,
synchronize: true,
}),
}];
使导入的工作方式如下:
constructor(
private connection: Connection,
) {
this.repository = connection.getRepository(Project);
}
在这种情况下nestjs
无法找到依赖项。我想问题出在typeorm
,它被编译成简单的es5函数。但也许有解决方案吗?
更新
我找到了可接受的解决方案nestjs typeorm module,但不明白为什么我的Connection
类没有工作,但它适用于字符串。希望@ kamil-myśliwiec将有助于理解。
modules: [
TypeOrmModule.forRoot(
[
Build,
Project,
],
{
type: 'postgres',
host: 'localhost',
port: 5432,
username: 'postgres',
password: 'postgres',
database: 'testo',
entities: [
Build,
],
logging: true,
synchronize: true,
}),
],
// And the n inject like this by entity name
@InjectRepository(Build) private repository: Repository<Build>,
答案 0 :(得分:0)
在这里,我将分享一些示例,这些示例可以帮助您解决或重现此问题。
在Config / config.ts
import "reflect-metadata";
import { ConnectionOptions } from "typeorm";
import { abctable } from "../DatabaseEntities/abctable";
import { deftable } from "../DatabaseEntities/deftable";
import { ghitable } from "../DatabaseEntities/ghitable";
export let dbOptions: ConnectionOptions = {
type: "DatabaseType",
host: "HostAddress",
port: Port,
username: "UserName",
password: "Password",
database: "DatabaseName",
entities: [abctable, deftable, ghitable],
synchronize: true
}
在server.ts中
import { createConnection, createConnections } from 'typeorm';
import * as appConfig from './Config/config';
createConnection(appConfig.dbOptions).then(async connection => {
console.log("Connected to DB");
}).catch(error => console.log("TypeORM connection error: ", error));
谢谢