Create method chain before object exists

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();
  })

Now, my question is:

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

Answers (2)

MTCoster
MTCoster

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

Mike Samuel
Mike Samuel

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

Related Questions