mysqlconnectionnestjstypeorm

Check if connection was successful using NestJs and Mysql


The title speaks for itself, I am starting to learn NestJS and I would like to know if it's possible to, for example console.log or other way, know if a connection with a database was successful.

When I run the npm run start:dev , everything compile fine but I am still not sure if I was able to connect to the database or not.

Note: I am using import { TypeOrmModule } from '@nestjs/typeorm/dist/typeorm.module';

Edit: If you have this line after running your app (on your terminal)

TypeOrmModule dependencies initialized

That means that you have successfuly estabilished a conection with your database


Solution

  • If your connection is failing you will get a very clear error in your console:

    [Nest] 1274   - 04/09/2021, 11:24:52 AM   [TypeOrmModule] Unable to connect to the database. Retrying (1)... +2042ms
    Error: getaddrinfo ENOTFOUND localhast
        at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:66:26)
    

    or

    Unable to connect to the database. Retrying (2)... +3009ms
    error: password authentication failed for user "mysql"
        at Parser.parseErrorMessage (nest/node_modules/pg-protocol/src/parser.ts:357:11)
        at Parser.handlePacket (nest/node_modules/pg-protocol/src/parser.ts:186:21)
        at Parser.parse (nest/node_modules/pg-protocol/src/parser.ts:101:30)
        at Socket.<anonymous> (nest/node_modules/pg-protocol/src/index.ts:7:48)
        at Socket.emit (events.js:315:20)
        at Socket.EventEmitter.emit (domain.js:483:12)
        at addChunk (_stream_readable.js:295:12)
        at readableAddChunk (_stream_readable.js:271:9)
        at Socket.Readable.push (_stream_readable.js:212:10)
        at TCP.onStreamRead (internal/stream_base_commons.js:186:23)
    
    

    or

    [Nest] 1412   - 04/09/2021, 11:32:36 AM   [TypeOrmModule] Unable to connect to the database. Retrying (2)... +3008ms
    error: database "example" does not exist
        at Parser.parseErrorMessage (nest/node_modules/pg-protocol/src/parser.ts:357:11)
        at Parser.handlePacket (nest/node_modules/pg-protocol/src/parser.ts:186:21)
        at Parser.parse (nest/node_modules/pg-protocol/src/parser.ts:101:30)
        at Socket.<anonymous> (nest/node_modules/pg-protocol/src/index.ts:7:48)
        at Socket.emit (events.js:315:20)
        at Socket.EventEmitter.emit (domain.js:483:12)
        at addChunk (_stream_readable.js:295:12)
        at readableAddChunk (_stream_readable.js:271:9)
        at Socket.Readable.push (_stream_readable.js:212:10)
        at TCP.onStreamRead (internal/stream_base_commons.js:186:23)
    

    No message means success