farrow-js/farrow

[disscussion] why not use zod?

Closed this issue · 2 comments

the farrow schema is good to started, but seems not find the enum and some thing like transform ...

and the question is

  1. how to define a enum data struct?
  2. maybe can get some docs for how it(code gen) works?

thx!

zod and other schema-builder are not well for codegen and seamless recursive schema support.

For enum you can juse use Union instead.

And farrow-schema is limited itself for just type-check without other validation logic support like max, range which can't be codegen in type level.

For more validation support, user can extend Schema to add custom verify rules but they can not be used to build request/response schema in farrow-api, they can only be used in the middleware function in server side.

import { RegExp } from 'farrow-schema/validator';

/**
 * custom validator without codegen support
 */
const Reg0 = RegExp(/123/);
const validateReg0 = createSchemaValidator(Reg0);

const definition = {
  input: {
    [Type]: String,
  },
  output: {
    [Type]: Int,
  },
};

const incre = Api(definition, (input: string): number => {
  // use in server side
  const result = validateReg0(input);

  if (result.isOk) {
    return 123
  } else {
    return 0
  }
});


// more complex custom schema

class DateType extends ValidatorType<Date> {
  validate(input: unknown) {
    if (input instanceof Date) {
      return this.Ok(input)
    }

    if (typeof input === 'number' || typeof input === 'string') {
      return this.Ok(new Date(input))
    }

    return this.Err(`${input} is not a valid date`)
  }
}

class EmailType extends ValidatorType<string> {
  validate(input: unknown) {
    if (typeof input !== 'string') {
      return this.Err(`${input} should be a string`)
    }

    if (/^example@farrow\.com$/.test(input)) {
      return this.Ok(input)
    }

    return this.Err(`${input} is not a valid email`)
  }
}

// now user can not be used in request/response too
const User = Struct({
  name: String,
  email: EmailType,
  createAt: DateType,
})

const validateUser = createSchemaValidator(User)

ok got that, thx master!