Skip to content

Instantly share code, notes, and snippets.

@knowthen
Last active April 26, 2019 23:00
Show Gist options
  • Save knowthen/ff3709d50164ef3d90d6e8d8d64db29c to your computer and use it in GitHub Desktop.
Save knowthen/ff3709d50164ef3d90d6e8d8d64db29c to your computer and use it in GitHub Desktop.
import sql from 'mssql';
import humps from 'humps';
const pool = new sql.ConnectionPool({
user: 'db_user_name_goes_here',
password: 'db_user_password_goes_here',
host: 'localhost',
database: 'hackerbook',
});
function logQuery (sql, params) {
console.log('BEGIN-------------------------------------');
console.log('SQL:', sql);
console.log('PARAMS:', JSON.stringify(params));
console.log('END---------------------------------------');
};
async function query(sql, params) {
// I'm not sure if this (connect()) should be called once, or if calling this multiple
// times is ok... from the docs, it seems like this is ok. I don't have
// a sql server to test against
const pool = await sql.connect(config);
logQuery(sql, params);
try{
const request = pool.request();
params.forEach(([name, value]) => {
request.input(name, value);
});
const result = request.query(sql);
// I think the recordset property is an array, so this should work
const rows = humps.camelizeKeys(result.recordset)
return {rows};
}
catch(err) {
console.log(err)
}
}
/*
Example usage:
await query("select * from book where id = @book_id", [['book_id', 1]]);
*/
export default query;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment