Created
April 17, 2021 01:59
-
-
Save jeremybradbury/d5d03cb39b8032a8ec0e63cd77a5690e to your computer and use it in GitHub Desktop.
nodejs pg helper - upsertRow
This file contains hidden or 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
// you'll likely want the pool creation in another file & imported here instead of a new pool | |
const pool = new require("pg").Pool(); // left here for completeness | |
// import { pool } from "../db" | |
// usage example: `upsertRow("profile", {id:"999", bio: "I like to..." image: "https://..."})` | |
const upsertRow = async (table, row = {}) => { | |
try { | |
const fields = Object.keys(row); | |
const values = Object.values(row); | |
let q = `INSERT INTO ${table} (${fields.reduce((x, y) => `"${x}", "${y}"`)}) | |
VALUES(${values.reduce((x, y) => `'${x}', '${y}'`)}) | |
ON CONFLICT ("id") DO UPDATE`; | |
for (let i = 0; i < fields.length; i++) { | |
if (fields[i].includes("id")) continue; | |
q += ` SET ${fields[i]} = EXCLUDED.${fields[i]}`; | |
} | |
// console.info("query",q); // uncomment for troubleshooting | |
({ | |
rows: [row], // extract first row into row variable | |
} = await pool.query(q)); | |
} catch (err) { | |
console.error( | |
`upsertRow(${table},${JSON.stringify(row)})` | |
); | |
console.error(err) | |
return false; | |
} | |
return row; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just wanted to point out this in an intentional antipattern placed here for a student excercise.
Hopefully it's obvious: don't actually use this!