🔪

JSのタグ付きテンプレートリテラルでSQLバインドを楽ちんに

2022/06/23に公開

バィンドでさ、

sql実行する関数("INSERT INTO posts values ($1,$2,current_timestamp",[req.body.title, req.body.content])

だとヵヵくのマヂめんどくさぃょね
もぅむり...。こぅしちゃぇばぃぃよね

// license: MIT

/**
 * usage: sql`insert into hoge values (2,${`(select json_agg(users) from users)`})` //out: ["insert into hoge values (2,$1)",["(select json_agg(users) from users)"]]
 * @template T
 * @type {(r:TemplateStringsArray,...v:T[])=>[string, T[]]}
 */
export const sql = (r,...rawValues) => {
  const valuearr = [...new Set(rawValues)]
  const values = new Map(valuearr.map((v,i) => [v,i+1]))
  return [r.map(
    (v,i)=> i<r.length-1 ? v + "$"+values.get(rawValues[i]) : v
  ).join(""),valuearr]
}
example: sql`insert into hoge values (2,${`(select json_agg(users) from users)`})`
response: ["insert into hoge values (2,$1)",["(select json_agg(users) from users)"]]

ぅぇのれぃは、そのままじっこぅできるょ(ラベル)

gistはここ: https://gist.github.com/ikasoba/a7b8d1bc5d59405dc0632f1afad0d6c3

Discussion