2
votes

I use TypeORM with expressjs but I am unable to the connection after bootstrapping it.

In my app.js, I have

import 'reflect-metadata';
import { createConnection, ConnectionOptions } from 'typeorm';
// Other imports

const app: Application = express();

// Setup express-async-errors
asyncHandler;

createConnection({
  "type": "sqlite",
  "database": "database.sqlite",
  "synchronize": true,
  "logging": true,
  "entities": [
    path.join(__dirname, "app/entity/**/*.js")
  ],
}).then(async connection => {

  // Set Environment & middleware
  middleware(app);

  // setup routes
  routes(app);

  app.listen(3000);
}).catch(error => console.log(error));

 export default app;

Then, I have a UsersController.ts which is linked to a the user routes

import { Request, Response } from 'express';
import { User } from '../entity/User';
import { getConnection } from "typeorm";

class UsersController {
  private userRepository;

  constructor() {
    this.userRepository = getConnection().getRepository(User);
  }

  async index(req: Request, res: Response) {
    const users = await this.userRepository.find();

    res.json({
      users
    });
  }
}

export default UsersController;

However, if I try to run the above code, I always get

ConnectionNotFoundError: Connection "default" was not found..

[ 'ConnectionNotFoundError: Connection "default" was not found.', ' at new ConnectionNotFoundError (C:[user]\node_modules\typeorm\error\ConnectionNotFoundError.js:19:28)', ' at ConnectionManager.get (C:[user]\node_modules\typeorm\connection\ConnectionManager.js:38:19)', ' at Object.getConnection (C:[user]\node_modules\typeorm\index.js:268:35)', ' at new UsersController (C:[user]\build\app\controllers\users.controller.js:7:41)', ' at Object. (C:[user]\build\app\routes\users.route.js:12:19)', ' at Module._compile (internal/modules/cjs/loader.js:689:30)', ' at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)', ' at Module.load (internal/modules/cjs/loader.js:599:32)', ' at tryModuleLoad (internal/modules/cjs/loader.js:538:12)', ' at Function.Module._load (internal/modules/cjs/loader.js:530:3)' ] }

I have checked the typeORM online documentation and what I have above is the recommended way to setup TypeORM so, I am confused.

Any pointer, in the right direction will be appreciated.

1

1 Answers

2
votes

The error occurs because the initialization code "TypeORM" runs asynchronously and the rest of the code runs forward. The solution is that you need to register all express routing in the block after then (createConnection ({}).then ). The documentation has an example of working with express:

http://typeorm.io/#/example-with-express