Reputation: 57
I'm currently having a bad time with typeOrm, I don't know why but express is getting initialized before my connection to the database with typeOrm So I get an error "Connection default not found"
here's the code
Typeorm.config.ts
import {Connection, createConnection} from 'typeorm';
export function connectToDb(): Promise<Connection> {
return createConnection({
type: 'postgres',
url: process.env.TYPEORM_URL,
synchronize: false,
logging: true,
entities: [process.env.TYPEORM_ENTITIES],
migrations: ["../../migrations/*.ts"],
cli: {migrationsDir: process.env.TYPEORM_MIGRATIONS_DIR}
})
}
Room.repository
import {getRepository} from 'typeorm';
import {Room} from '../entities/Room';
const roomRepository = getRepository(Room)
export async function getAllRooms(): Promise<Room[]> {
return await roomRepository.find()
}
this repo is used by my router, here's my app.ts
import * as express from 'express'
import * as bodyParser from 'body-parser';
import * as PassportJs from './passport';
import cors from 'cors';
import logger from './config/logger';
import "reflect-metadata";
import * as dotenv from 'dotenv';
dotenv.config();
import roomRouter from './routes/room.route';
import {connectToDb} from './config/typeorm.config';
const passport = PassportJs.initPassport();
async function main(): Promise<void> {
logger.info('connecting to database...')
await connectToDb()
logger.info('connected to database')
const app = express();
app.use(bodyParser.json());
app.use(passport.initialize());
app.use(cors());
app.use(roomRouter);
app.listen(3000, () => {
logger.info(`API is running on port ${3000}`);
});
}
main().catch(error => {
logger.error(error)
process.exit(1)
})
Can you help me?
Thank
Upvotes: 0
Views: 912
Reputation: 51
From the code snippets you have share, I guess const roomRepository = getRepository(Room)
is being called before the await connectToDb()
. Creating a repo needs connection.
Upvotes: 1