farrow-js / farrow

A Type-Friendly Web Framework for Node.js
https://www.farrowjs.com
MIT License
770 stars 37 forks source link

Bug(farrow-schema): Literal validation in non-strict mode #163

Closed tqma113 closed 2 years ago

tqma113 commented 2 years ago

The current implement of Literal validation is

Validator.impl<S.LiteralType>(S.LiteralType, (schema) => ({
  validate: (input, options) => {
    const value = schema.value
    if (input === value) {
      return Ok(input as S.Literals)
    }

    if (options?.strict === false && typeof value !== 'string') {
      if (typeof value === 'number') {
        const result = parseNumberLiteral(input)
        if (result.isOk) return result
      } else if (typeof value === 'boolean') {
        const result = parseBooleanLiteral(input)
        if (result.isOk) return result
      }
    }

    return SchemaErr(`${input} is not a literal ${value}`)
  },
}))

in non-strict mode, after parsing input to number or boolean, if should it compare the value and the parsing result?

Like this

if (options?.strict === false && typeof value !== 'string') {
  if (typeof value === 'number') {
    const result = parseNumberLiteral(input)
    if (result.isOk && result.value === value) return result
  } else if (typeof value === 'boolean') {
    const result = parseBooleanLiteral(input)
    if (result.isOk && result.value === value) return result
  }
}