首页 > 解决方案 > “ConnectionNotFoundError:未找到连接“默认”” - 类属性

问题描述

我正在学习 NodeJS,任务是构建一个简单的消息传递服务。老师使用的是 SQLite3,但我决定使用 Postgres,因为它是我们公司项目中使用的数据库。

错误:“ConnectionNotFoundError:未找到连接“默认””

// server.ts

import 'reflect-metadata';
import express from 'express';
import { createConnection } from 'typeorm';

import router from './router';

(async () => {
  const PORT = 3333;

  console.log('before');
  await createConnection();
  console.log('after');

  const app = express();

  app.use(express.json());
  app.use(express.urlencoded({ extended: true }));

  app.use(router);

  app.listen(PORT, () => {
    console.log(`App is running on port ${PORT}`);
  });
})();

我有以下MessagesService

// this works just fine
class MessagesService {
  async create({ user_id, text, admin_id }: MessagesCreateInterface): Promise<Message> {
    const repository = getCustomRepository(MessagesRepository);

    const message = repository.create({
      admin_id,
      text,
      user_id,
    });

    await repository.save(message);

    return message;
  }


  async listByUser(user_id: string): Promise<Array<Message>> {
    const repository = getCustomRepository(MessagesRepository);
    const messages = await repository.find({ user_id });
    return messages;
  }
}

由于getCustomRepository在两个函数中都被调用,并尝试将其转换为类属性:

class MessagesService {
  repository: MessagesRepository;

  constructor() {
    console.log('constructor');
    this.repository = getCustomRepository(MessagesRepository);
  }
  ...
}

但后来我明白了ConnectionNotFoundError: Connection "default" was not found.

实验

  1. 使用setTimeoutinside constructor:访问连接。

  2. Consoles.log:我得到“之前”和“构造函数”打印,但不是“之后”。

有人可以帮我理解发生了什么吗?由于我使用的是 async/await,MessageService因此在建立连接之前不应调用。我在这里打破了一些模式吗?

标签: node.jstypescripttypeorm

解决方案


您没有将连接选项传递给 TypeORM,因此它不知道如何连接和设置连接(这是默认连接)。

不带参数调用await createConnection()将从文件中加载连接选项,并且(据我所知)您没有任何ormconfig.X文件。

要将连接选项传递给 TypeORM,您有三个选项:

  1. 连接选项对象
    请参阅https://typeorm.io/#/connection调用createConnection({ ... })
    时直接传递连接选项(对象) 。 例子:
const connection = await createConnection({
    type: "postgres",
    host: "localhost",
    port: 5432,
    username: "test",
    password: "test",
    database: "test"
});
  1. ormconfig.X 文件
    参见https://typeorm.io/#/using-ormconfig。在项目根目录中
    加载一个ormconfig.[extension]文件。
    支持的 ormconfig 文件扩展名有:.json、.js、.ts、.env、.yml 和 .xml。
    示例(ormconfig.json):
{
   "type": "postgres",
   "host": "localhost",
   "port": 5432,
   "username": "test",
   "password": "test",
   "database": "test"
}
  1. 环境变量
    https://typeorm.io/#/using-ormconfig/using-environment-variables
    TypeORM 自动在环境变量或项目根目录中的.envormconfig.env中搜索连接选项(靠近 package.json)。
    例子:
TYPEORM_CONNECTION = postgres
TYPEORM_HOST = localhost
TYPEORM_PORT = 5432
TYPEORM_USERNAME = test
TYPEORM_PASSWORD = test
TYPEORM_DATABASE = test

推荐阅读