bookshelf-spotparse
A Bookshelf.js plugin that makes formatting, parsing and finding models easier.
See also: bookshelf-update, a plugin that makes updating models more intuitive.
Installation
- Install with npm using
npm i bookshelf-spotparse
- After creating a bookshelf instance, call the plugin method:
const bookshelf = knex;bookshelf;
- SpotParse can now be used on all models.
Usage
SpotParse allows you to create an arrangement for the variables inside your models. You can now specify for each variable how they should be inserted and read to and from the database:
// Model definitionlet User = bookshelf;
The above code will encrypt a password (if present) when
storing the model to the database and decrypt the password
(if present) when getting a user out of the database.
This makes it so the database always has the encrypted password
and user.get('password')
will always return the decrypted password.
To use an unformatted field to retrieve a model from the database
the spot()
function can be used:
User;// Prints: decryptedpassword
In this case the password will be formatted (encrypted) before being passed to the database query.
Overriding
WARNING: SpotParse makes the format and parse functions static to be used with spot()
.
Overriding the format
and parse
functions inside your model will
result in spot({key: value})
no longer parsing the value properly.
You can however override the format
and parse
functions in the
static (constructor) part of your module, for instance:
// Model definitionlet User = bookshelf;
Leaving out this.formatArrangement()
will nullify the workings of the
arrangement
property, the spot()
method will still use the overridden code.