I'm integrating TypeORM and I have encountered some problems, for example:
I created an entity(User)
import {Entity, PrimaryGeneratedColumn, Column} from "typeorm";
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column({
length: 100
})
firstName: string;
@Column({
length: 100
})
lastName: string;
@Column({
length: 100
})
email: string;
@Column()
password: string;
@Column()
createdAt: Date;
@Column()
updatedAt: Date;
}
and create user folder with this content:
users.zip
main problem is in users.ts, if I do getCustomRepository(UserRepository) I get
connectionnotfounderror: connection "default" was not found
that is related to getConnection() or createConnection() before that getCustomRepository(UserRepository) for this I create a shared class:
import { Connection, ConnectionManager, getConnectionOptions, createConnection, getConnectionManager } from 'typeorm'
import { SnakeNamingStrategy } from 'typeorm-naming-strategies'
import 'reflect-metadata'
/**
* Database manager class
*/
export class Database {
private connectionManager: ConnectionManager
constructor() {
this.connectionManager = getConnectionManager()
}
public async getConnection(): Promise<Connection> {
console.log('getConnection');
const CONNECTION_NAME = `default`
let connection: Connection
if (this.connectionManager.has(CONNECTION_NAME)) {
connection = await this.connectionManager.get(CONNECTION_NAME)
if (!connection.isConnected) {
connection = await connection.connect()
}
}
else {
const connectionOptions = await getConnectionOptions();
Object.assign(connectionOptions, { namingStrategy: new SnakeNamingStrategy() });
connection = await createConnection(connectionOptions)
}
return connection
}
}
function getConnection() here is async so it returns a promise and dont know how manage this on users.ts for export getUser endpoint.
const db: Database = new Database();
export const getUser: ApiHandler = db.getConnection().then((connection: Connection): ApiHandler => {
const repo: UserRepository = connection.getCustomRepository(UserRepository);
const service: UsersService = new UsersService(repo);
const controller: UsersController = new UsersController(service);
return controller.getUser;
});
So I get
Type 'Promise(ApiHandler)' is not assignable to type 'ApiHandler'