Last active
December 4, 2019 15:50
-
-
Save nickav/1203916177ffee2f5169ea8258e60dd2 to your computer and use it in GitHub Desktop.
This file contains 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
// Converts SQL query from named parameters :param to [param] | |
export const sqlParams = ( | |
sql: string, | |
params: Record<string, any> | |
): [string, any[]] => { | |
const matches = sql.split(/([^:]:[A-z]+[A-z0-9])/g); | |
let i = 0; | |
const nextParams: any[] = []; | |
const nextSql = matches.map((str, index) => { | |
const isParam = index % 2 === 1; | |
if (!isParam) { | |
return str; | |
} | |
const prefix = str.slice(0, 1); | |
const paramName = str.slice(2); | |
const nextToken = `$${++i}`; | |
const param = params[paramName]; | |
if (!params.hasOwnProperty(paramName)) { | |
console.warn(`sqlParams - missing parameter: '${paramName}'`); | |
} | |
nextParams.push(param); | |
return prefix + nextToken; | |
}).join(''); | |
return [nextSql, nextParams]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment