How I can manage mysql connection with typeorm on Serverless APIGateway?

Viewed 1548

I'm coding a APIGateway using serverless-framework for AWS Lambda with typescript + typeorm + mysql. My problem is when I try get my custom repository

users.repository.ts

import { User } from "../../entity/User";
import { EntityRepository, Repository } from "typeorm";

@EntityRepository(User)
export class UserRepository extends Repository<User> {

    getUser(userId: number) {
        return this.findOne(userId);
    }

    findByName(firstName: string, lastName: string) {
        return this.findOne({ firstName, lastName });
    }
}

I'm getting

connectionnotfounderror: connection \"default\" was not found

if I try in users.ts getCustomRepository(UserRepository) instead of connection.getCustomRepository(UserRepository) I found a class for manage this

database.ts

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
    }
}

but I'm having problems with async function when I try to export controller endpoint

Type 'Promise' is not assignable to type 'ApiHandler'

users.ts

import { ApiHandler } from '../../../shared/api-interfaces';
import { UsersController } from './users.controller';
import { UserRepository } from './users.repository';
import { UsersService } from './users.service';
import { getRepository, getCustomRepository, Connection } from 'typeorm';
import { Database } from '../../../shared/database';

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;
});

users.service.ts

import { NotFoundResult, InternalServerErrorResult } from '../../../shared/errors';
import { User } from '../../entity/User';
import { UserRepository } from './users.repository';
import { GetUserResult } from './users.interfaces';

export class UsersService {

  public constructor(private readonly userRepository: UserRepository) {
  }

  public getUser(id: number): Promise<GetUserResult> {
    return new Promise((resolve: (result: GetUserResult) => void, reject: (reason: NotFoundResult) => void): void => {
      this.userRepository.getUser(id).then((user: User) => {
        if (!user) {
          reject(new NotFoundResult('UNKNOWN_USER', 'There is no user with the specified ID!'));
          return;
        }

        const result: GetUserResult = {
          user
        };

        resolve(result);

      }).catch((error) => {
        reject(new InternalServerErrorResult('DATABASE_ERROR', error));
      });

    });
  }
}
0 Answers
Related