如何在无服务器APIGateway上使用typeorm管理mysql连接?

时间:2019-01-18 00:12:27

标签: typescript aws-lambda serverless typeorm

我正在使用Typescript + typeorm + mysql为AWS Lambda使用无服务器框架编写APIGateway。我的问题是当我尝试获取自定义存储库时

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

我要

  

connectionnotfounderror:找不到连接\“ default \”

如果我尝试使用users.ts getCustomRepository(UserRepository)而不是connection.getCustomRepository(UserRepository),则会发现一个用于管理此问题的类

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

但是当我尝试导出控制器端点时,异步功能出现了问题

  

类型“ Promise”不能分配给类型“ 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 个答案:

没有答案