Permalink
Browse files

Support for parsing JSON schemas with references.

  • Loading branch information...
1 parent 564d84b commit da2771c9de692f362a967058b0535544a29bc6c3 @molnarg committed Aug 18, 2012
Showing with 41 additions and 1 deletion.
  1. +1 −1 lib/Schema.js
  2. +40 −0 lib/extensions/Schema.js
View
@@ -96,7 +96,7 @@ Schema.session = session
Schema.fromJS = def()
-Schema.fromJSON = def()
+Schema.fromJSON = Schema.session(def())
Schema.extend = function(descriptor) {
View
@@ -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.