Replies: 1 comment
-
// vine.ts
import db from '@adonisjs/lucid/services/db'
import { Dictionary } from '@adonisjs/lucid/types/querybuilder'
import vine, { VineString } from '@vinejs/vine'
import { FieldContext } from '@vinejs/vine/types'
type Options = {
table: string
column: string
// ID excluded when modifying data
notin?: number[]
where?: Dictionary<any, string>
}
const uniqueRule = async (value: unknown, options: Options, field: FieldContext) => {
if (typeof value !== 'string') {
return
}
const { table, column, where, notin } = options
const query = db.from(table).select('id').where(column, value)
if (where) {
query.where(where)
}
if (Array.isArray(notin)) {
query.whereNotIn('id', notin)
}
const row = await query.first()
if (row) {
field.report('The {{ field }} field is not unique', 'unique', field)
}
}
const validation = vine.createRule(uniqueRule)
VineString.macro('unique', function (this: VineString, options: Options) {
return this.use(validation(options))
})
declare module '@vinejs/vine' {
interface VineString {
unique(options: Options): this
}
}
// validation
vine.object({
label: vine.string().trim().minLength(2).maxLength(6).unique({
table: 'tags',
column: 'label',
}),
}) |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Base on this documentation about extending schema classes.
before extending VineString unique method
create preload vine
node ace make:preload vine -r
after extending VineString unique method
results when payload code is not unique
Beta Was this translation helpful? Give feedback.
All reactions