Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Template literals function for use with callbacks #960

Merged
merged 2 commits into from
Dec 27, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,14 @@ sql.connect(config, err => {

console.dir(result)
})

// Using template literal

const request = new sql.Request()
request.query(request.template`select * from mytable where id = ${value}`, (err, result) => {
// ... error checks
console.dir(result)
})
})

sql.on('error', err => {
Expand Down
12 changes: 12 additions & 0 deletions lib/base/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,18 @@ class Request extends EventEmitter {
this.parameters = {}
}

/**
* Generate sql string and set imput parameters from tagged template string.
*
* @param {Template literal} template
* @return {String}
*/
template () {
dhensby marked this conversation as resolved.
Show resolved Hide resolved
const values = Array.prototype.slice.call(arguments)
const strings = values.shift()
return this._template(strings, values)
}

/**
* Fetch request from tagged template string.
*
Expand Down
7 changes: 7 additions & 0 deletions test/common/unit.js
Original file line number Diff line number Diff line change
Expand Up @@ -273,4 +273,11 @@ describe('Unit', () => {
command: 'select * from myTable where id in (@param1_0, @param1_1, @param1_2)'
})
})

it('tagged template literal request', () => {
dhensby marked this conversation as resolved.
Show resolved Hide resolved
const req = new sql.Request()
const sqlstr = req.template`select * from myTable where id = ${123}`
assert.strictEqual(sqlstr, 'select * from myTable where id = @param1')
assert.strictEqual(req.parameters.param1.value, 123)
})
})