Knex: Custom Builder Functions

Created on 15 Jul 2016  ·  3Comments  ·  Source: knex/knex

I'd like to add some custom functions to knex which I have to use all the time but i'm finding it hard to get them to work.

They are:
knex.selectOne
knex.selectZeroOrOne

Instead of doing first, selectOne does not apply a limit and instead throws an error if it gets more than one record back. This allows the author to catch particular errors particular early.

I started with:

knex.client.QueryBuilder.prototype.selectOne = function (columns) { 
    const args = new Array(arguments.length);
    for (let i = 0; i < args.length; i++) {
      args[i] = arguments[i];
    }
    this.select.apply(this, args);
    this._method = 'first';
    //this.limit(1);
    return this;
}

but obviously the check on how many records get returned has to happen after the results have come back

Would you be able to point me in the right direction?

planned for 1.0

Most helpful comment

@tgriesser I have waiting for this feature for while and start modifying the QueryBuilder prototype. It will be so great to have an interface to extend the query builder.

👍

All 3 comments

Just FYI This code won't work in 0.12, you'll need to require knex/lib/query/builder directly to modify that prototype.

For 1.0 I'll plan to define a standard way to customize the query builder chain like you're trying to do above, and with the addition of "hooks", you'll be able to easily setup post-result transforms.

@tgriesser I have waiting for this feature for while and start modifying the QueryBuilder prototype. It will be so great to have an interface to extend the query builder.

👍

@tgriesser - How far are we away from 1.0?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mattgrande picture mattgrande  ·  3Comments

rarkins picture rarkins  ·  3Comments

fsebbah picture fsebbah  ·  3Comments

nklhrstv picture nklhrstv  ·  3Comments

arconus picture arconus  ·  3Comments