Plugins
Plugins modify the behaviour of Field
, Model
and Query
classes simply by
overloading their methods.
To load plugins into the ORM, use Knorm.prototype.use
:
const { knorm } = require('@knorm/knorm');
const { knormRelations } = require('@knorm/relations');
const { Model, Query } = knorm({
/* knorm options */
}).use(
knormRelations({
/* plugin options */
})
);
see @knorm/relations for this plugin's documentation
Available plugins
Plugin | Description |
---|---|
@knorm/postgres | enables connecting to postgres |
@knorm/to-json | adds a toJSON method to Model |
@knorm/relations | enables SQL joins |
@knorm/soft-delete | enables soft-deletion |
@knorm/paginate | enables counting and paginating rows |
@knorm/timestamps | enables timestamps |
Creating custom plugins
A Knorm plugin can be any named function or an object with an init
function
and a name
property. See
Knorm.prototype.use
more info.
When a plugin is loaded via Knorm.prototype.use
, the function (or object's
init
function) is called with the knorm
instance. The plugin can then modify
the classes on the instance:
const preventDelete = knorm => {
class YouShallNotDelete extends knorm.Query {
async delete() {
throw new Error('deleting is not allowed!');
}
}
knorm.updateQuery(YouShallNotDelete);
};
const { Model } = knorm().use(preventDelete);
Model.delete().catch(console.log);
// result:
// Error('deleting is not allowed!')
info
Knorm
provides some utility methods for plugins to update the instance's
classes:
Knorm.prototype.updateTransaction
Knorm.prototype.updateModel
Knorm.prototype.updateQuery
Knorm.prototype.updateField
Knorm.prototype.updateConnection