diegohaz / schm

Composable schemas for JavaScript and Node.js

Home Page:https://git.io/schm

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Validate type field doesn't work as expected

scbj opened this issue · comments

commented

Hi! Nice work out there, i'm unfortunally front of a issue. Code now:

import schema from 'schm'

const foo = schema({
  shouldCry: {
    required: true,
    type: Boolean
  }
})
const output = await foo.validate({ shouldCry: "i'm not a boolean" })

It's validate this successfully and return:

{
  shouldCry: true
}

But the type is specified in the schema... And this behavior also happens on other types, in short the attribute 'type' does not seem to work 🤔.

Regards, Sacha.

commented

The type validator is there for cases when you define another schema as the type. So, it can validate schema structure altogether:

const fooSchema = schema(...)
const barSchema = schema({
  foo: { type: fooSchema },
})

What you want is probably something as typeof. It still doesn't exist in the library, but I'm open for this.

commented

That's how a type validator can be added to the schema:

const schema = require('schm')
const Type = require('type-of-is')

const withTypeValidator = prevSchema => prevSchema.merge({
  validators: {
    // modifying type validator
    type: (value, option) => ({
      valid: Type.is(value, option.optionValue),
      message: option.message || `{PARAM} must be of type ${option.optionValue.name}`
    })
  },
  parsers: {
    // we need to modify the type parser
    // otherwise it will convert type before we validate
    type: value => value
  }
})

const mySchema = schema(
  {
    name: { type: String }
  },
  withTypeValidator
)

await mySchema.validate({ name: 1 })

See this in action: https://runkit.com/diegohaz/schm-typeof

Hi @diegohaz

I've implemented your approach to validate types, but now the problem is that types are not converted. For example:

const mySchema = schema({
    postId: { type: Number }
  }, withTypeValidator)

mySchema.validate({ postId: '1' }).then(parsed => {
  console.log(typeof parsed.postId) // => "string"
});

What I'd love is to have parsed.postId as Number. Any idea of how could I accomplish that?

Thanks!