Created
July 27, 2019 03:58
-
-
Save Arsfiqball/b922c62edcdc77f11fd1925c52e9eb7f to your computer and use it in GitHub Desktop.
Validate unique value of database using knex.js and validate.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const assert = require('assert') | |
const validate = require('validate.js') | |
const db = require('./db') // instance of knex | |
// custom validation | |
validate.validators.unique = function (value, options, key) { | |
assert.ok(!!options.table) | |
assert.ok(!!options.column) | |
assert.ok(!!options.db) | |
return options | |
.db(options.table) | |
.where(options.column, value) | |
.first(options.column) | |
.then(row => Promise.resolve(row ? `${key} is already used` : undefined)) | |
.catch(console.error) | |
} | |
// usage | |
const constraints = { | |
username: { | |
unique: { | |
table: 'users', | |
column: 'username', | |
db: db | |
}, | |
} | |
} | |
validate | |
.async({ username: 'someone' }, constraints) | |
.then(() => console.log('ok')) | |
.catch(err => console.log(err)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment