Interpolate variable inside tagged template

71 views Asked by At

I'm using tagged templates to build a query with its params.

function query (strings, ...args) {
    return {
        sql: strings.join('?'),
        params: args
    }
}

const storeId = '417-123';
const id = 10;
const res = query`select * from trad.customers where store_id = ${ storeId } and customer_id = ${ id }`;
// res.sql: select * from trad.customers where store_id = ? and customer_id = ?;
// res.params: [ '417-123', 10 ];

Sometimes I need to pass a variable which cannot be passed as a SQL parameter (for instance, a table name) to the query. I'm stuck with this...

const nim = '0850204';
const id = 143;
const res = query`select * from _${ nim }_ tickets where tick_id = ${ id }`;
// what I get:
// res.sql: select * from _?_ tickets where tick_id = ?;
// res.params: [ '0850204', 143 ];

// what I'd like
// res.sql: select * from _0850204_ tickets where tick_id = ?;
// res.params: [ 143 ];

How can I get around this ? Thank you for your help :)

EDIT : I used a special char as a flag to tell when to replace the variable directly... This way, when the char # is found I replace directly the following value. I'm pretty sure we can do better but I don't know how...

function query (strings, ...args) {

    const del = [];
    const replace = [];
    let sql = strings
        .map((data, index) => {
            if (data.endsWith('#') === false) return data;
            replace.push(args[index]);
            del.push(index);
            return data;
        })
        .join('?');

    args = args.filter((d, index) => del.includes(index) === false);

    let n = 0;
    while (sql.includes('#?')) {
        sql = sql.replace('#?', replace[n]);
    }

    return { sql, params: args };
}

const nim = '0850204';
const id = 143;
// Notice the '#'
const res = query`select * from _#${ nim }_ tickets where tick_id = ${ id }`;
// res.sql: select * from _0850204_ tickets where tick_id = ?;
// res.params: [ 143 ];
0

There are 0 answers