【发布时间】:2022-03-17 01:06:54
【问题描述】:
我正在学习 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.。
实验
-
在
constructor内使用setTimeout:访问连接。 -
Consoles.log:我得到“之前”和“构造函数”打印,但没有“之后”。
有人可以帮助我了解发生了什么吗?由于我使用的是 async/await,所以在建立连接之前不应调用 MessageService。我在这里打破了一些模式吗?
【问题讨论】:
标签: node.js typescript typeorm