Is there a way to use different host (same database) for reading and writing in database?

Viewed 307

I just started learning nestJS and came from Laravel. How do I make it such that I am using different database host when reading (SELECT statements) and writing (INSERT statements) within the same database?

In Laravel (the one I have experience with), it looks something like this:

'mysql' => [
    'read' => [
        'host' => ['192.168.1.1'],
    ],
    'write' => [
        'host' => ['196.168.1.2'],
    ],
    'driver' => 'mysql',
    'database' => 'database',
    'username' => 'root',
    'password' => '',
],

As you can see from above, I am using the same database but different host for read/write. Is it possible to do the same with NestJS? I'm using typeORM if it matters.

1 Answers

Sure, TypeORM supports read/write replication (details here).

Here's an example (master instance is used for write operations, random slave instance is used for reading).

{
  type: "mysql",
  replication: {
    master: {
      host: "192.168.1.1",
      port: 3306,
      username: "test",
      password: "test",
      database: "test"
    },
    slaves: [{
      host: "192.168.1.2",
      port: 3306,
      username: "test",
      password: "test",
      database: "test"
    }]
  }
}
Related