Last active
December 14, 2020 19:24
-
-
Save DhyanRathore/29f028b80d20eaf3d306f4f9b319f8a8 to your computer and use it in GitHub Desktop.
Azure Function: Node.js app to read PostgreSQL data and return JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Azure Function: Node.js code to read PostgreSQL data 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 | |
}; | |
// Create query to execute against the database | |
const querySpec = { | |
text: 'SELECT * FROM public.subcountry' | |
} | |
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