Tagged Templates and Template Query
What are Tagged Templates?
✓ Advanced form of Template Literals
✓ Parse Template literal with a function
✓ First argument is array of strings. Remaining arguments are related to the expressions
✓ Tag function need not return a string
✓ raw
property allows us to access the raw strings as it is i.e. as they were entered without the escape sequence.
✓ Use String.raw()
method to create the raw strings
Example:
//Templated Query for TypeScript
const where = TemplatedQuery.fragments(" WHERE ", " AND ");
if (id) {
where = where.add `CustomerID = ${id}`;
}
if (name) {
where = where.add `Name like ${name + '%'}`;
}
const q = TemplatedQuery.create `SELECT * FROM Customers ${where}`;
const tq = q.toQuery();
Here, If you look in the above example TemplatedQuery.create and where.add are Tagged Templates.
What will happen if id
was empty?
If id
was empty, corresponding condition will be skipped and first AND
will disappear.
Can you give me the advantage of using the Templated Query?
Yes, ofcourse
✓ It can prevent SQL Injection attack
✓ It can combine multiple Template Literals (String literals allowing embedded expressions)
Like | Comment | Save | Share |