We have so many new features in ES2015+ that now I seem to be forgetting them.

I was recently throwing together a little node microservice that was heavily utilising some rather fancy sql via knex. Although the builder that knex offers is pretty handy, I had a few complex queries that required almost always dropping down into using knex.raw to write raw sql statements.

This all works fine; however, with a larger number of parameters making sure that you’ve correctly lined up the question marks in the statement to the values supplied in the following array becomes quite a pain. (Yes, I could have just dropped down to using the named params in mysql2 module, but everything else in the app was using knex so I didn’t).

Template Strings in ES6, the things that give us nice expression interpolation, have (afaik) a little-used advanced form which allows modifying the result of a template string with a function. Lifting the example straight from the MDN section on tagged template strings:

Effectively prefix the template string with a function name, and that function will get passed an array of strings for each portion of text, and an array of evaluated expressions to do something with.

With this, the text I need for the sql statement can simply be created by joining the array of strings with a question mark for the parameter placeholders, and the values themselves come in the order I need to place in the array for knex.raw. Doing that is as simple as:

This can then be used by either passing in a knex instance, or a transaction that also has a raw method.

So yeah, tagged template strings are a thing, and with just a couple of lines of code can do pretty useful things.