在标记模板内插值变量

时间:2018-09-17 07:28:06

标签: javascript tagged-templates

我正在使用带标签的模板来构建带有参数的查询。

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 ];

有时我需要传递一个不能作为SQL参数(例如,表名)传递给查询的变量。我被困住了...

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 ];

我该如何解决? 谢谢您的帮助:)

编辑: 我使用特殊的char作为标记来指示何时直接替换变量...这样,当找到char #时,我将直接替换以下值。我很确定我们可以做得更好,但是我不知道如何...

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 个答案:

没有答案