Skip to content

Instantly share code, notes, and snippets.

@DhyanRathore
Last active September 10, 2021 18:59
Show Gist options
  • Save DhyanRathore/37d3dd73b5db5c65ad182abdcb1754da to your computer and use it in GitHub Desktop.
Save DhyanRathore/37d3dd73b5db5c65ad182abdcb1754da to your computer and use it in GitHub Desktop.
Azure Function: Node.js app to read PostgreSQL data with query parameter and return JSON
// Azure Function: Node.js code to read PostgreSQL data with query parameter and return results as JSON
// Author: Dhyanendra Singh Rathore
// Import the pg (node-postgres) library
const pg = require('pg');
// Entry point of the function
module.exports = async function(context, req) {
// Define variables to store connection details and credentials
const config = {
host: process.env["POSTGRES_SERVER_NAME"],
user: process.env["POSTGRES_USER"],
password: process.env["POSTGRES_USER_PASS"],
database: 'iso3166',
port: 5432,
ssl: true
};
// req.query.country will be passed as query variable in the URL
const values = [req.query.country];
// Create query to execute against the database
const text = 'SELECT * FROM public.subcountry subcon' + (values[0] != undefined ? ' WHERE subcon."country" IN ($1)' : '');
const querySpec = {
text: text,
values: (values[0] != undefined ? values : '')
}
try {
// Create a pool of connections
const pool = new pg.Pool(config);
// Get a new client connection from the pool
const client = await pool.connect();
// Execute the query against the client
const result = await client.query(querySpec);
// Release the connection
client.release();
// Return the query resuls back to the caller as JSON
context.res = {
status: 200,
isRaw: true,
body: result.rows,
headers: {
'Content-Type': 'application/json'
}
};
} catch (err) {
context.log(err.message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment