Search code examples
mysqldatabasetypescriptknex.js

How do you return a query from knex typescript operations instead of results?


I am using knex to perform operations on my sql db. Is there a way I can sort-of lazy execute the query? My code looks like this

const results = await knex({dbconfig})('table1')
                           .select('col1').where('...')

I want to make some typescript operations and check some conditions to perform further operations. If I try to perform them by simply writing results.where('...') it fails saying TypeError: results.where is not a function.

What I am doing right now is:

if (condition1){
const results = await knex(..).(some operations)
    }
else{
const results = await knex(..).(some operations + some other operarations)
    }

Is there a better way to do this?


Solution

  • The trick here, as I think you've discovered, is to use the object that Knex returns. However, you don't have to reassign it each time, just call the method on it. So:

    async function getCustomers(options) {
      const customers = knex('customers').where({ someCondition });
    
      if (options.region) {
        customers.where({ region: options.region });
      }
    
      return customers;
    }
    

    Note that return await is redundant in an async function: you'll have to await in the calling code anyway, so you're really just returning a promise.