Home Blog CV Projects Patterns Notes Book Colophon Search

Node PostgreSQL

30 Nov, 2023

Calling PostgreSQL from Node.

import pg from "pg";
import  express  from 'express'
import eah from 'express-async-handler'
import { write } from "fs";
const app = express()
const { Pool } = pg;
const port = 80


const pool = new Pool({
    host: process.env.PGHOST,
    database: process.env.PGDATABASE,
    user: process.env.PGUSER,
    port: process.env.PGPORT ? parseInt(process.env.PGPORT) : undefined,
    password: process.env.PGPASS,
    ssl: process.env.PGSSL ? process.env.PGSSL.toLowerCase()  === 'true' : false,
})

app.get('/', eah(async (req, res, next) => {
  res.send('Hello!')
}))

app.get('/qry-pool', eah(async (req, res, next) => {
  console.log('Making a sample database query')
  const result = await pool.query("SELECT * FROM auth.organisation")
  res.json(result.rows)
}))

app.get('/page', eah(async (req, res, next) => {
  renderTwoColPage((data) => {res.write(data)}, "Messages", (write)=>{write('First')}, (write)=>{write('Second')})
  res.end()
}))



app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})


// Better handling of SIGINT and SIGTERM for docker
process.on('SIGINT', function () {
  console.log('Received SIGINT. Exiting ...')
  process.exit()
})

process.on('SIGTERM', function () {
  console.log('Received SIGTERM. Exiting ...')
  process.exit()
})

Comments

Be the first to comment.

Add Comment





Copyright James Gardner 1996-2020 All Rights Reserved. Admin.