imbrn/v8n

Schema testing against an object that extends the schema

dbismut opened this issue · 10 comments

Hi, thanks for this lib, I just started using it and it's a joy (no pun^^).

I may have missed something in the docs, but is testing an object extending the schema supposed to return true?

const validation = v8n().schema({
  id: v8n()
    .number()
    .positive(),
  name: v8n()
    .string()
    .minLength(4)
});

validation.test({
  id: 1,
  name: "Luke"
}); // true

validation.test({
  id: 1,
  name: "Luke",
  lastname: "Skywalker"
}); // also true?

If so, maybe it would be great to add it in the docs?

Yes, this is intended. It works much like an interface would validate a class if you will. Imagine simple interface.

interface Animal {
  name: string;
}

class Dog implements Animal {
  name: string;
  race: string;
}

A lot of classes could be made from this, they only need to implement what is there. That's how interfaces usually work and that is how schema works.

I guess an exact schema validation may be an interesting thing. Gotta ask @imbrn what he thinks.

Ok! Just to explain my usecase, I'm in a situation where I want to detect the schema of an object. To do so I'm testing the object against a list of schemas. First schema from the list that matches the object is the one.

My problem comes as one schema is Point2d {x,y} and another is Point3d {x,y,z}. You see me coming but if Point2d is tested before Point3d, all {x,y,z} objects will be marked as Point2d.

It's no big deal as in my case I just need to test Point3d before Point2d but I was curious to know if I was missing something.

I get the idea of an exact schema validation for multiple use cases. Worth discussing.

I guess checking if the number of keys are equal would suffice?

I guess so. You can add it if you want and pull request.

I'm just not sure about the api though? schema().strict()?

Why not add an optional argument to schema?

function schema(schema, strict = false) {
  // ...
}

Strict would be a modifier if anything, meaning it would be chained the other way.

v8n()
  .strict.schema({})
  .test({});

I honestly like both. The modifier is harder to implement though a tad more elegant.

Oh I agree.

Plus if strict is set, we should first check if the number of keys are equal and skip further validation if not. That's probably faster to check negatives than with chaining strict.

imbrn commented

Hey guys, how's it going?

So @dbismut, as @brfrth explained, the schema acts most like an interface, so the intention is indeed to validate extended objects. But I liked the idea of having a strict mode for that. If you guys agree, I think we should go with the modifier based version.

Closing this in favor of #191, thanks for your idea and input.