I was trying to use typeorm with typedi, and there were some problem. I want to use typeorm for ORM, typegraphql for GraphQL, and DI for typedi. And now I'm trying to implementing typedi with typeorm, but there are some problem I get:
Error I got
{
"message": "Cannot get Connection with name \"default\" from the ConnectionManager. Make sure you have created the connection and called \"useContainer(Container)\" in your application before establishing a connection and importing any entity into TypeORM.",
"exception": {
"connectionName": "default",
"name": "ManagerNotFoundError",
"stacktrace": [
"ManagerNotFoundError: Cannot get Connection with name \"default\" from the ConnectionManager. Make sure you have created the connection and called \"useContainer(Container)\" in your application before establishing a connection and importing any entity into TypeORM."
]
}
}
However, I'd already placed useContainer(Container)
above the connection settings.
src/index.ts (Entry File)
import './utils/env'
import 'reflect-metadata'
import { Server } from './server'
import { Database } from './database'
import logger from './utils/logger'
import { Container } from 'typeorm-typedi-extensions'
import { useContainer } from 'typeorm'
const server = new Server()
const database = new Database()
useContainer(Container)
void database
.connect()
.then(() => {
logger.info('Database connected')
void server.listen().then((server) => {
const { port } = server.address() as { port: number }
logger.info(`Server started on port ${port}`)
})
})
.catch((reason) => {
throw new Error(`Databse Error: ${reason as string}`)
})
And these is my userRepository file
src/entities/user/UserRepository.ts
@Service()
@EntityRepository(User)
export class UserRepository extends Repository<User> {
// (...)
}
And this is my UserService file
src/graphql/user/UserService.ts
@Service()
export default class UserService {
@InjectRepository(User)
private readonly userRepository: UserRepository
// (...methods)
}
Lastly, this is my UserResolver file
src/graphql/user/UserResolver.ts
@Service()
@Resolver(() => User)
export class UserResolver {
@Inject()
private readonly userService: UserService
(...)
}
SOLVED ::
node_modules/typeorm-typedi-extensions/cjs/container-registrations.const.js
Line 10
FROM
typedi_1.Container.set({ id: typeorm_1.ConnectionManager, type: typeorm_1.ConnectionManager });
TO
typedi_1.Container.set({ id: typeorm_1.ConnectionManager, type: typeorm_1.ConnectionManager, global: true });