fastify-atdatabases-pg
v1.0.0
Published
This module provides a way to use postgressql database.
Maintainers
Readme
fastify-atdatabases-pg
This module provides a way to connect to PostgreSQL database using @databases/pg
Install
npm i fastify-atdatabases-pgUsage
Add it to you project with register and you are done!
const fastify = require('fastify')()
fastify.register(require('fastify-atdatabases-pg'), {
connectionString: 'postgres://postgres:postgres@localhost:5432/postgres',
bigIntMode: 'string'
})
fastify.get('/', async (req, reply) => {
const result = await fastify.pg.db.query(fastify.pg.sql`SELECT NOW()`)
return reply.send(result)
})
fastify.listen({ port: 3000 }, err => {
if (err) throw err
})You can also connect with different databases using namespaces to differentiate each other:
const fastify = require('fastify')()
fastify.register(require('fastify-atdatabases-pg'), {
namespace: 'primary',
connectionString: 'postgres://postgres:postgres@primary:5432/primary',
bigIntMode: 'string'
})
fastify.register(require('fastify-atdatabases-pg'), {
namespace: 'secondary',
connectionString: 'postgres://postgres:postgres@secondary:5432/secondary',
bigIntMode: 'string'
})
fastify.get('/primary', async (req, reply) => {
const result = await fastify.pg.primary.db.query(fastify.pg.primary.sql`SELECT NOW()`)
return reply.send(result)
})
fastify.get('/secondary', async (req, reply) => {
const result = await fastify.pg.secondary.db.query(fastify.pg.secondary.sql`SELECT NOW()`)
return reply.send(result)
})
fastify.listen({ port: 3000 }, err => {
if (err) throw err
})Health Checks
Use ensureReady() for health check endpoints or to wake up database:
fastify.get('/health/db', async (req, reply) => {
try {
await fastify.pg.ensureReady()
return { status: 'healthy' }
} catch (err) {
reply.status(503)
return { status: 'unhealthy', error: err.message }
}
})Documentation
More details about @databases/pg documentation, see @databases/pg
