Created
April 25, 2017 21:21
-
-
Save jeffmcmahan/e9da088172583898678ebd45bf57c005 to your computer and use it in GitHub Desktop.
SQL template tag
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
'use strict' | |
/** | |
* Maps the given value to a value expressible in SQL. | |
* @param {*} val | |
* @return {String} | |
*/ | |
function sqlValue(val) { | |
if (val === null) return null | |
if (val === "'null'") return 'null' | |
if (val === 'null') return 'null' | |
if (typeof val === 'undefined') return 'null' | |
if (typeof val === 'number') return val | |
if (typeof val === 'string') return `'${val}'` | |
if (typeof val === 'object') return `'${JSON.stringify(val)}'` | |
return val.toString() | |
} | |
/** | |
* Template tag function for creating SQL statements. | |
* @param {String[]} strings | |
* @param {...*} values | |
* @return {String} | |
*/ | |
module.exports = function(strings, ...values) { | |
let output = '' | |
strings.forEach((str, i) => { | |
if (i >= values.length) output += str | |
else output += str + sqlValue(values[i] || null) | |
}) | |
return output | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment