nestjs+typeorm如何配置连接多数据库呢?

技术栈说明:nestjs,typerom;

期待的结果

要求能用仓储模式,通过泛型传入entity类名,ORM帮我自动生成简单的CRUD SQL呢?说明:以下代码案例中,我仅通过ormconfig.js,链接了单数据库。

相关代码

1、仓储代码:repository.service.ts

import { Injectable } from "@nestjs/common";
import { Repository, ObjectID, getManager } from "typeorm";
import { ResultList } from "common/interfaces/result.interface";

export interface Id {
    id: string | number | Date | ObjectID;
}

@Injectable()
export class RepositoryService<T extends Id> {

    constructor(
        private repository: Repository<T>
    ) { }

    async findAll(index: number, size: number, query: any): Promise<ResultList<T>> {
        return new Promise<ResultList<T>>(async (x) => {
            let result: ResultList<T> = {
                list: await this.repository.find({ skip: size * (index - 1), take: size }),
                count: await this.repository.count(),
                query: {
                    index: index,
                    size: size
                }
            }
            x(result);
        })
    }

    async findOne(id: string | number | Date | ObjectID): Promise<T> {
        return await this.repository.findOne(id);
    }

    async create(entity: any): Promise<any> {
        return await this.repository.save(entity);
    }

    async update(entity: T): Promise<any> {
        let index = await this.repository.findOne(entity.id);
        if (index) {
            Object.assign(index, entity);
            await getManager().transaction(async transactionalEntityManager => {
                await transactionalEntityManager.save(index);
            })

            return index
        }
    }

    async remove(id: string | number | Date | ObjectID): Promise<any> {
        let entity = await this.repository.findOne(id);
        return await this.repository.remove(entity);
    }

}

2、Service代码:zone-locations.service.ts

@Injectable()
export class ZoneLocationsService extends RepositoryService<ZoneLocation> {

    constructor(
        @InjectRepository(ZoneLocation)
        private readonly zoneLocationsRepository: Repository<ZoneLocation>,
    ) { 
        super(zoneLocationsRepository);
    }

    async findAll(index: number, size: number, query: any):Promise<ResultList<ZoneLocation>>{
        return new Promise<ResultList<ZoneLocation>>(async (x) => {
            let result: ResultList<ZoneLocation> = {
                list:  await this.zoneLocationsRepository.find({order:{locationCode:"ASC"}, skip: size * (index - 1), take: size }),
                count: await this.zoneLocationsRepository.count(),
                query: {
                    index: index,
                    size: size
                }
            }
            x(result);
        })
    }
}

3、orm链接字符串:
image.png

阅读 8.4k
1 个回答
✓ 已被采纳新手上路,请多包涵

亲自打,终于解决了!!
1、ormconfig.json

clipboard.png
2、app.module.ts

clipboard.png
3、stk_department.module.ts

clipboard.png

4、stk_department.service.ts 服务

clipboard.png
5、控制器:

import { Controller, UseInterceptors } from "@nestjs/common";
import { ControllerService } from "../../common/services/controller.service";
import { StkDepartmentService } from "./services/stk_department.service";
import { StkDepartment } from "./entities/stk_department.entity";

@Controller('stk_department')
export class StkDepartmentController extends ControllerService<StkDepartment> {

    constructor(entityService: StkDepartmentService) {
        super(entityService)
    }
}

6、目录

clipboard.png
7、然后CRUD代码全部自动生成了,效果:

clipboard.png

8、如果需要源码,可以联系我,谢谢!!
9、折腾一番,这个需求也解决了:
就是用 getConnection('链接名称'),然后用query()直接执行SQL。
删除掉ormconfig.json文件,然后把配置写在app.module.ts里,居然就成功了。
搞不懂,这不符合我的需求(其实也可以,暂时让运维帮我替换app.module.ts文件),因为上线后,运维是想用文件替换来给我设置生产环境的。
image.png
`async testConnection(){

    const connection2 = await getConnection('connection2');
    return  connection2.query('select * from stk_department');
}`

参考链接:
1、https://stackoverflow.com/questions/51994541/nestjs-typeorm-use-two-or-more-databases/51995362
参考资料说typeorm有bug,用ormconfig.json也是不成功的。气人!!有待深究,朋友们如果有其他方法,也请赐教,谢谢!!

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏