This plugin adds a unique validation for Objection.js models.
NOTE: Unique validation at update only works with $query
methods.
npm i objection-unique --save
yarn add objection-unique
// Import objection model.
const Model = require('objection').Model;
// Import the plugin.
const unique = require('objection-unique')({
fields: ['email', 'username'],
identifiers: ['id']
});
// Mixin the plugin.
class User extends unique(Model) {
static get tableName() {
return 'User';
}
}
/**
* Insert.
*/
// Insert one user.
await User.query().insert({ email: 'foo', username: 'bar' });
try {
// Try to insert another user with the same data.
await User.query().insert({ email: 'foo', username: 'bar' });
} catch (e) {
// Exception with the invalid unique fields
//
// {
// email: [{
// keyword: 'unique',
// message: 'email already in use.'
// }],
// username: [{
// keyword: 'unique',
// message: 'username already in use.'
// }
// }
}
/**
* Update/Patch.
*/
// Insert one user.
await User.query().insert({ email: 'foo', username: 'bar' });
// Insert the user that we want to update.
const user = await User.query().insertAndFetch({ email: 'biz', username: 'buz' });
try {
user.$query().update({ email: 'foo', username: 'buz' });
// user.$query().patch({ email: 'foo' });
} catch (e) {
// Exception with the invalid unique fields
//
// {
// email: [{
// keyword: 'unique',
// message: 'email already in use.'
// }]
// }
}
fields: The unique fields.
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'],
identifiers: ['id']
});
Run the tests from the root directory:
npm test
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.
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.