molnarg / js-schema

Simple and intuitive schema validator
http://molnarg.github.com/js-schema/
MIT License
388 stars 45 forks source link

add #toJSON method for classes #33

Open bcherny opened 9 years ago

bcherny commented 9 years ago

before:

let Cat = schema({
  bornOn: Date
})
Cat.toJSON()
// => {
//  required: true
// }

after:

let Cat = schema({
  bornOn: Date
})
Cat.toJSON()
// => {
//  required: true,
//  type: "Date"
// }
molnarg commented 9 years ago

How would you implement the inverse of this operation? Also, JSON Schema is standardised formally, does the standard accept an extension like that?

molnarg commented 9 years ago

In the inverse, you could say that the class could be looked up based on name, but that's not true. A very simple example is when a class is defined in a closure, so the class is unaccessible in the global namespace.

And how would you serialise anonymous functions as constructors? E.g. var Class = function() { /* ... */ }

bcherny commented 9 years ago

ah, i didn't realize that #toJSON is json-schema compatible. json-schema properties are extensible, though i'm not sure if values are extensible as well.

this will work equally well for non-globals as well as globals. the schema definition accepts a Constructor function, and there is no requirement for the Constructor to be globally available.

it also degrades gracefully for non-named functions:


function Foo(){}
let Bar = function(){}

let mySchema = schema({
  foo: Foo,
  bar: Bar
})

mySchema.toJSON()

// => {
//   foo: {
//     required: true,
//     type: "Foo"
//   }
//   bar: {
//     required: true,
//     type: "Function"
//   }
// }