Skip to content

Commit

Permalink
Support for parsing JSON schemas with references.
Browse files Browse the repository at this point in the history
  • Loading branch information
Gábor Molnár committed Aug 18, 2012
1 parent 564d84b commit da2771c
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/Schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ Schema.session = session

Schema.fromJS = def()

Schema.fromJSON = def()
Schema.fromJSON = Schema.session(def())


Schema.extend = function(descriptor) {
Expand Down
40 changes: 40 additions & 0 deletions lib/extensions/Schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,43 @@ function renewing(ref) {
}

Schema.self = schema.self = renewing(new SchemaReference())

Schema.fromJSON.def(function(sch) {
if (sch.id == null && sch['$ref'] == null) return

var id, session = Schema.session

if (!session.deserialized) session.deserialized = { references: {}, subscribers: {} }

if (sch.id != null) {
// This schema can be referenced in the future with the given ID
id = sch.id

// Deserializing:
delete sch.id
var schemaObject = Schema.fromJSON(sch)
sch.id = id

// Storing the schema object and notifying subscribers
session.deserialized.references[id] = schemaObject
;(session.deserialized.subscribers[id] || []).forEach(function(callback) {
callback(schemaObject)
})

return schemaObject

} else {
// Referencing a schema given somewhere else with the given ID
id = sch['$ref']

// If the referenced schema is already known, we are ready
if (session.deserialized.references[id]) return session.deserialized.references[id]

// If not, returning a reference, and when the schema gets known, resolving the reference
if (!session.deserialized.subscribers[id]) session.deserialized.subscribers[id] = []
var reference = new SchemaReference()
session.deserialized.subscribers[id].push(reference.resolve.bind(reference))

return reference
}
})

0 comments on commit da2771c

Please sign in to comment.