Skip to content

add #toJSON method for classes#33

Open
bcherny wants to merge 1 commit into
molnarg:masterfrom
bcherny:master
Open

add #toJSON method for classes#33
bcherny wants to merge 1 commit into
molnarg:masterfrom
bcherny:master

Conversation

@bcherny

@bcherny bcherny commented Apr 25, 2015

Copy link
Copy Markdown

before:

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

after:

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

@bcherny bcherny changed the title add #toJSON method for constructors add #toJSON method for classes Apr 25, 2015
@molnarg

molnarg commented May 3, 2015

Copy link
Copy Markdown
Owner

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

@molnarg

molnarg commented May 3, 2015

Copy link
Copy Markdown
Owner

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

bcherny commented May 3, 2015

Copy link
Copy Markdown
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants