Node-postgres: named parameters query (nodejs) Node-postgres: named parameters query (nodejs) sql sql

Node-postgres: named parameters query (nodejs)


There is a library for what you are trying to do. Here's how:

var sql = require('yesql').pgclient.query(sql("SELECT * FROM foo WHERE id = :id AND color = :color")({id: 22, color: 'blue'}));


I have been working with nodejs and postgres. I usually execute queries like this:

client.query("DELETE FROM vehiculo WHERE vehiculo_id= $1", [id], function (err, result){ //Delete a record in de db    if(err){        client.end();//Close de data base conection      //Error code here    }    else{      client.end();      //Some code here    }  });


QueryConvert to the rescue. It will take a parameterized sql string and an object and converts it to pg conforming query config.

type QueryReducerArray = [string, any[], number];export function queryConvert(parameterizedSql: string, params: Dict<any>) {    const [text, values] = Object.entries(params).reduce(        ([sql, array, index], [key, value]) => [sql.replace(`:${key}`, `$${index}`), [...array, value], index + 1] as QueryReducerArray,        [parameterizedSql, [], 1] as QueryReducerArray    );    return { text, values };}

Usage would be as follows:

client.query(queryConvert("SELECT * FROM foo WHERE id = :id AND color = :color", {id: 22, color: 'blue'}));