Dev-2019
Dev-2019

Reputation: 557

String interpolation of a string stored in a variable

I am trying to prepare some SQL query for Amazon Athena with dynamic 'WHERE' conditions in JavaScript. The query was saved on one variable in another file. How to add custom WHERE condition to it?

Pseudocode that I am trying to achieve,

file1.js

module.exports.queryFromFile1 = 'SELECT * Name FROM Contact WHERE Name = ?';

file2.js

const {queryFromFile1} = require('./file1.js');

const newQuery = queryFromFile1,['Jane']; 
console.log(newQuery); // 'SELECT * Name FROM Contact WHERE Name = 'Jane'

Can anyone suggest to me a proper method to do it. my current solution is posted below.

file1.js

module.exports.queryFromFile1 = 'SELECT * Name FROM Contact WHERE Name = {stringToReplace}';

file2.js

const {queryFromFile1} = require('./file1.js');

const newQuery = queryFromFile1.replace("{stringToReplace}", "'Jane"); 
console.log(newQuery); // 'SELECT * Name FROM Contact WHERE Name = 'Jane'

Upvotes: 1

Views: 1340

Answers (2)

Robert Moskal
Robert Moskal

Reputation: 22553

I use a little helper function that let's you use straight es6 string interpolation in a round about way:

const template= (template, ctx) => {
   const script = new vm.Script('`' + template + '`')
   return script.runInNewContext(ctx)
}

const results = template('hello ${foo}', {foo:'jane'})

But, if you just need to do do a simple interpolation, why not just export the sql as a function?

const queryFromFile1 = str => (`SELECT * Name FROM Contact WHERE Name = ${str}`)

const query = queryFromFile1('Jane')

Upvotes: 2

starikcetin
starikcetin

Reputation: 1486

As mentioned in the comments, you should not handle SQL statements with raw strings.

However, for a non-security critical parts of your code (for example, taking in a date format string from component props), this is how I prefer to do this:

const stringProducer = (insert) => `This was inserted: ${insert}`;

Then use like this:

const string = stringProducer("foo");

Upvotes: 0

Related Questions