Unique validation for Objection.js

This plugin adds a unique validation for Objection.js models.
NOTE: Unique validation at update only works with $query
methods.
Installation
NPM
npm i objection-unique --save
Yarn
yarn add objection-unique
Usage
Mixin the plugin
const Model = require('objection').Model;
const unique = require('objection-unique')({
fields: ['email', 'username', ['phone_prefix','phone_number']],
identifiers: ['id']
});
class User extends unique(Model) {
static get tableName() {
return 'User';
}
}
Validate insert
await User.query().insert({ email: 'foo', username: 'bar' });
try {
await User.query().insert({ email: 'foo', username: 'bar' });
} catch (e) {
}
Validate update/patch
await User.query().insert({ email: 'foo', username: 'bar' });
const user = await User.query().insertAndFetch({ email: 'biz', username: 'buz' });
try {
user.$query().update({ email: 'foo', username: 'buz' });
} catch (e) {
}
Options
fields: The unique fields. Compound fields can be specified as an array
identifiers: The fields that identifies the model. (Default: ['id'])
These options can be provided when instantiating the plugin:
const unique = require('objection-unique')({
fields: ['email', 'username', ['phone_prefix', 'phone_number']],
identifiers: ['id']
});
Tests
Run the tests from the root directory:
npm test
Contributing & Development
Contributing
Found a bug or want to suggest something? Take a look first on the current and closed issues. If it is something new, please submit an issue.
Develop
It will be awesome if you can help us evolve objection-unique
. Want to help?
- Fork it.
npm install
.- Hack away.
- Run the tests:
npm test
. - Create a Pull Request.