【问题标题】:How to solve the TypeORM to use at application and the tests如何解决在应用程序和测试中使用的 TypeORM
【发布时间】:2021-08-30 20:32:33
【问题描述】:

我在使用 TypeORM 之前遇到问题,在我进行配置之前它可以处理我通过 Insomnia 发送的请求,但是,我无法让它在测试中使用它,例如创建连接、关闭连接和清理数据基础。

我最终更改了 ORM 配置,以便我可以在测试中执行这些操作,但现在当我想通过 Insomnia 进行测试时它开始不起作用。

ormconfig.json 当前

所以我不知道如何在主项目文件中使用它

import { createConnection, getConnection } from 'typeorm';

const connection = {
  async create(){
    await createConnection();
  },

  async close(){
    await getConnection().close(); 
  },

  async clear(){
    const connection = getConnection();
    const entities = connection.entityMetadatas;

    entities.forEach(async (entity) => {
      const repository = connection.getRepository(entity.name);
      await repository.query(`DELETE FROM ${entity.tableName}`);
    });
  },
};

export default connection;

ormconsig.json 之前

这样,在项目的初始化文件中,我只是做了一个导入import from "./infra/typeorm"

import { createConnection, getConnectionOptions } from 'typeorm';

interface IOptions {
  host: string;
}

export default getConnectionOptions().then(options => {
  const newOptions = options as IOptions;
  newOptions.host = 'database_clina';
  createConnection({
    ...options,
  });
});

src/index.ts

import "reflect-metadata";
import connection from "./infra/typeorm";
import express from "express";

import { usersRoutes } from "./routes/users.routes";

const app = express();

app.use(express.json());

app.use("/users", usersRoutes);

export { app };

错误

UnhandledPromiseRejectionWarning: ConnectionNotFoundError: Connection "default" was not found.

【问题讨论】:

    标签: typescript typeorm


    【解决方案1】:

    suspect you are missing some steps,例如这是生成连接所必需的..."migration:generate": "npm run typeorm -- migration:generate --config src/config/ormconfig.json --connection --name "

    添加这行代码console.log("env", process.env.NODE_ENV, connection!.name); 来调试你的连接。

    现在仔细检查文档:如何创建连接https://github.com/typeorm/typeorm/blob/master/docs/connection.md

    我通常同时拥有默认配置和生产配置,然后切换到生产。


    1. 假设您使用如下所示的 someModule/或 TypeOrmModule 设置 TypeORM,然后检查您是否在模块中首先设置您的连接...
     // Debug connection
     console.log("env", process.env.NODE_ENV, connection!.name);
    

    TypeOrmModule.forRoot({
          type: config.db.type,
          host: config.db.host,
          port: config.db.port,
          username: config.db.user,
          password: config.db.password,
          database: config.db.database,
          entities: [
            __dirName + '/../../dtos/entities/*.entity.js',
          ]
        })
    
    1. 仔细检查并在函数内部建立连接,然后创建/获取对 repo 的访问权限。

    //  this should usually work from inside a function or a factory function so its available.
     const ticketsRepository = getRepository(Tickets); inside a function 
    

    如果所有这些都不起作用,请遵循此模式。为了方便将来访问,为连接创建一个factory 函数,然后根据需要导入它。请参阅此处github sample

    //factory function
    import { getRepository } from 'typeorm/browser';
    import { UserEntity, UserModel } from './schema';
    
    export function getUserRepository() {
      return getRepository<UserModel>(UserEntity);
    }
    
    ____
    
    // now import and consume it
    import { getUserRepository } from '...';
    
    getUserRepository().findOne(1);
    

    1. 除了ormconfig.json(顺便说一句,您在问题中拼错了这个,假设它是 typeo 但仔细检查并没有什么坏处),您还需要在您的package.json 中使用这些命令来引导生成连接。
    "typeorm": "ts-node -r tsconfig-paths/register ./node_modules/.bin/typeorm",
    "migration:generate": "npm run typeorm -- migration:generate --config src/config/ormconfig.json --connection  --name ",
    "migration:run": "npm run typeorm -- migration:run"    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-07
      • 2018-10-11
      • 2015-05-13
      • 2021-05-28
      • 1970-01-01
      • 2021-10-22
      • 1970-01-01
      相关资源
      最近更新 更多