js-schema icon indicating copy to clipboard operation
js-schema copied to clipboard

add #toJSON method for classes

Open bcherny opened this issue 10 years ago • 3 comments

before:

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

after:

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

bcherny avatar Apr 25 '15 00:04 bcherny

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

molnarg avatar May 03 '15 13:05 molnarg

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() { /* ... */ }

molnarg avatar May 03 '15 13:05 molnarg

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"
//   }
// }

bcherny avatar May 03 '15 19:05 bcherny