有很多我一直在做的操作,我希望能有一种方法来“扩展”康耐视来完成这些操作。
我想做这样的事情:
oneExists
result = knex.count(id).from('table').where({'code': 25})
if (result.length === 0) return false
if (result.length === 1) return true
throw an error
我希望能做些像
knex.oneExists.count('id').from('table').where({'code': 25}).
目前,我正在编写这样的代码:
KnexUtil.oneExists(knex.select('id').from('table').where({code: 25}))
会回报你的承诺
我看过knex代码库,我不确定:
发布于 2020-09-04 12:56:25
从v0.19.1开始,knex具有内置扩展QueryBuilder的能力
import Knex from 'knex'
Knex.QueryBuilder.extend('someFn', function (arg) {
console.log('Do Smth', arg)
return this
})
const knex = Knex({ client: 'pg' })
knex.select().from('table').someFn(0).toString()
发布于 2015-12-25 19:52:56
你当然可以。我建议您只创建自己的插件,如下所示:
// my-plugin.js
'use strict';
module.exports = function (Bookshelf) {
Bookshelf.Model = Bookshelf.Model.extend({
foo: function ( bar ) {
if( bar )
console.log('Method foo was called on a model with the arguments:', arguments.join(', '));
}
});
Bookshelf.Collection = Bookshelf.Collection.extend({
foo: function ( bar ) {
if( bar )
console.log('Method foo was called on a collection with the arguments:', arguments.join(', '));
}
});
};
然后在主应用程序文件中添加:
Bookshelf.plugin( require( './my-plugin' ) );
BookshelfJS插件基本上允许您扩展模型和集合(以及更多),这允许您添加自己的方法,或者覆盖现有的方法(同时仍然能够从插件中调用原始方法)。
为了更好地理解,您最好看看一些现有的BookshelfJS插件,其中一些已经在插件目录中附带了书架。
为了更好地理解插件的工作原理,另一个可能很好的插件是软删除插件。在这个插件中,您可以看到一些BookshelfJS方法是如何在模型和集合对象中被重写的,方法可以执行该方法的原始版本,然后返回已解析/修改的结果(#37-#59行和#37-#57行),以及添加全新的方法(#61-#72行)。
编辑:显然这是BookshelfJS而不是KnexJS,但是我没有看到为KnexJS创建插件的任何方法,因为它只是一个查询构造函数,所有真正的魔力都在ORM中
发布于 2022-05-24 10:37:04
如果使用TypeScript:
import { knex, Knex as KnexOriginal } from "knex";
declare module "knex" {
namespace Knex {
interface QueryBuilder {
customFunction<TRecord, TResult>(
value: number
): KnexOriginal.QueryBuilder<TRecord, TResult>;
}
}
}
knex.QueryBuilder.extend("customFunction", function (value: number) {
console.log("Custom Function:", value);
return this;
});
const pg = knex({ client: "pg" });
pg("table").select("*").customFunction(10).toString()
查看关于如何扩展knex的文档
https://stackoverflow.com/questions/34101998
复制相似问题