Reputation: 3001
Let's say I'm using knex to run queries against an SQL database. I chain a few methods to build the query.
For example:
const sqlConfig = require('./sql.config');
var knex = require('knex')(sqlConfig);
knex.select("*")
.from("books")
.where("author", "=", "José Saramago")
.then((rows) => {
console.log(rows);
})
.catch((err) => {
console.log(err);
})
.finally(() => {
knex.destroy();
})
Is there a way to store the method chain before the knex
object is created and call it later when it is created?
Something like this:
const methodChain = <<<
.select("*"),
.from("books"),
.where("author", "=", "José Saramago")
>>>
const sqlConfig = require('./sql.config');
var knex = require('knex')(sqlConfig);
knex
.methodChain()
.then((rows) => {
console.log(rows);
})
.catch((err) => {
console.log(err);
})
.finally(function() {
knex.destroy();
})
Upvotes: 1
Views: 32
Reputation: 6145
You could create a function that accepts the initial parameter in the chain:
function methodChain(in) {
return in.select("*")
.from("books")
.where("author", "=", "José Saramago");
}
methodChain(knex)
.then((rows) => {
console.log(rows);
})
.catch((err) => {
console.log(err);
})
.finally(function() {
knex.destroy();
})
Upvotes: 2
Reputation: 120516
Sure.
const methodChain = (x) => x
.select("*"),
.from("books"),
.where("author", "=", "José Saramago");
then later
methodChain(knex)
.then((rows) => {
console.log(rows);
})
.catch((err) => {
console.log(err);
})
.finally(function() {
knex.destroy();
})
Upvotes: 2