Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercepting knex.js queries pre-execution

I'm working on caching strategies for an application that uses knex.js for all sql related stuff. Is there a way to intercept the query to check if it can be fetched from a cache instead of querying the database?

Briefly looked into knex.js events, which has a query event. Doc: A query event is fired just before a query takes place, providing data about the query, including the connection's __knexUid / __knexTxId properties and any other information about the query as described in toSQL. Useful for logging all queries throughout your application.

Which means that it's possible to do something like (also from docs)

  .from('users')
  .on('query', function(data) {
    app.log(data);
  })
  .then(function() {
    // ...
  });

But is it possible to make the on query method intercept and do some logic before actually executing the query towards the database?

like image 511
Håvard Avatar asked Oct 19 '25 14:10

Håvard


1 Answers

I note that this suggestion is attached to a Knex GitHub issue (credit to Arian Santrach) which seems relevant:

knex.QueryBuilder.extend('cache', async function () {
    try {
        const cacheKey = this.toString()
        if(cache[cacheKey]) { 
            return cache[cacheKey]
        }
        const data = await this
        cache[cacheKey] = data
        return data
    } catch (e) {
        throw new Error(e)
    }
});

This would allow:

  knex('tablename').where(criteria).cache()

to check for cached data for the same query. I would think a similar sort of structure could be used for whatever your caching solution was, using the query's string representation as the key.

like image 69
Rich Churcher Avatar answered Oct 21 '25 03:10

Rich Churcher