jsonary-js / jsonary

Quickly assemble clients for JSON-based APIs (powered by JSON Schema)
http://jsonary.com/
MIT License
122 stars 14 forks source link

shouldn't schema default value be created without the need to click on + first? #117

Closed Ognian closed 10 years ago

Ognian commented 10 years ago

My problem is that when I provide a default value for an item in an object this item is not created until explicit creating this object by pressing the + item; When this item is readOnly I do not have the possibility to supply a default value (previously it was possible). From an UI point of view if there is a default value it should be created anyway without the need to press +, but I'm not quite sure ... What do you think?

Ognian commented 10 years ago

Until now, when creating a new object i used

jsonary.create({},...

this leads to setting an internal flag of ignoreDefaults to true. If is use

jsonary.create(undefined,...

then i get a + create for the whole object, which works correct. But is there a way to get the whole object created without having to press +create first?

Ognian commented 10 years ago

OK found a solution:

           if(!d && schemaUrl ){
                var s=Jsonary.getSchema(schemaUrl,function(s,call){
                    d=s.defaultValue();
                    //console.log("----->"+JSON.stringify(d));
                });

since I'm caching the url's this should be executed synchron...

Ognian commented 10 years ago

OK still a problem: s.defaultValue gets the top most default value and doesn't try to generate the default object define by subsequent properties....

geraintluff commented 10 years ago

Jsonary.create() is not meant for creating data according to particular schemas - it just wraps whatever value you put in.

If you are trying to create data that follows a particular schema (including required properties), then Schema objects (and SchemaLists) have methods for this: createData() and createValue(). They are basically the same, except createData() returns a Jsonary Data object with the schemas already applied, and createValue() returns a raw value.

Synchronous use:

data = schema.createData(); // from scratch
data = schema.createData({someInitial: 'value'}); // using a provided value as a base to work from

Asynchronous use: (fetches referenced schemas via AJAX if needed)

schema.createData(function (data) {
    ...
});
schema.createData({someInitial: 'value'}, function (data) {
    ...
});

Hybrid option: (returns data immediately so can be rendered, but then changes the value and adds schemas later)

var data = schema.createData(initialValue, true);
var data = schema.createData(initialValue, function() {
    // called when data changes value
});
Ognian commented 10 years ago

Ok this helped a lot, Thank you