Skip to content

Instantly share code, notes, and snippets.

@jeffmcmahan
Created Apr 25, 2017
Embed
What would you like to do?
SQL template tag
'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