adonisjs / validator

Schema based validator for AdonisJS
MIT License
116 stars 39 forks source link

I want to extend a base validator (reduce duplicity) - AdonisJS v.5 #149

Closed truc3651 closed 2 years ago

truc3651 commented 2 years ago

I have a PaginationValidator (used to valdiate api list data)

import { schema } from '@ioc:Adonis/Core/Validator'
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'

export default class PaginationValidator {
  constructor(protected ctx: HttpContextContract) {}

  public schema = schema.create({
    page: schema.number.optional([]),
    limit: schema.number.optional([]),
    order: schema.enum.optional(['ascend', 'descend']),
    orderBy: schema.string.optional(),
    keyword: schema.string.optional(),
  })

  public messages = {}
}

There's some apis has its own schema fields, and I want to expand PaginationValidator schema (page, limit ...) with these extended fields

import { schema } from '@ioc:Adonis/Core/Validator'
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'

export default class GetHospitalUsersListValidator {
  constructor(protected ctx: HttpContextContract) {}
  public refs = schema.refs({
    filterBy: ['hospitalId', 'prefectureId'],
  })

  public schema = schema.create({
    filterBy: schema.enum.optional(this.refs.filterBy),
  })

  public messages = {}
}

maybe

  public schema = schema.create({
    filterBy: schema.enum.optional(this.refs.filterBy),
  }).extend(PaginationValidator)
  // page, limit, keyword, order, orderBy, filter, filterBy

How can I extend the validator?

KageNoNeko commented 2 years ago

That's the neat thing: you don't :)

Just extract part of the schema into a function and use it in validators.

thetutlage commented 2 years ago

There are many ways to do it just using the language constructs. Following is a one simple example.

const sharedSchema = {
  page: schema.number.optional([]),
  limit: schema.number.optional([]),
  order: schema.enum.optional(['ascend', 'descend']),
  orderBy: schema.string.optional(),
  keyword: schema.string.optional(),
}

schema.create({
  ...sharedSchema
})

schema.create({
  ...sharedSchema,
  filterBy: schema.enum.optional(this.refs.filterBy)
})