Commits

Kenneth Jørgensen  committed 6ae412b

Implemented deep value handling in EventMessage

  • Participants
  • Parent commits eba2155

Comments (0)

Files changed (3)

File CHANGELOG.md

 * *Feature:* Implemented `toJSON()`  and `fromJSON()` on `EventMessage`.
 * *Feature:* Implemented `getRequired()`  and `getOptional()` on `EventMessage` for data retrieval.
 * *Feature:* Implemented `proxyErrors()` on `EventMessage` to handle automatic proxying of asynchronous errors.
+* *Feature:* `getOptional` and `getRequired` on `EventMessage` can now return deep values using JSON dot syntax.
 * *Fix:* `EventMessages` with empty datasets would throw undefined errors with `getRequired` and `getOptional`.
 
 ## 0.4.1 (2013-07-10)

File spec/core/EventMessageSpec.coffee

 		it "should throw errors on missing required values without a reply handler", ->
 			check = ->
 				msg.getRequired "doesntexist"
-			expect(check).toThrow("Variable \"doesntexist\" not found on message with address \"address\"")
+			expect(check).toThrow "Variable \"doesntexist\" not found on message with address \"address\""
 
-		it "should return deep values" # getRequired("a.b.c.d")
+		it "should return deep values", ->
+			msg = new EventMessage "address",
+				foo:
+					bar: "abc"
+			expect(msg.getOptional "foo.bar").toBe "abc"
+			expect(msg.getOptional "foo.a").toBe undefined
+			expect(msg.getRequired "foo.bar").toBe "abc"
+			test = -> msg.getRequired "foo.a"
+			expect(test).toThrow "Variable \"foo.a\" not found on message with address \"address\""
 
 		it "should support an empty dataset", ->
 			msg = new EventMessage "address", null

File src/core/EventMessage.coffee

 	# Returns a parameter message data.
 	# If the parameter is not present, `def` is returned.
 	getOptional: (param, def) ->
-		val = @data[param]
+		parts = param.split "."
+		val = @data[parts[0]]
+		# Iterate from second element onwards.
+		if parts.length > 1 then for part in parts.splice 1
+			if _.isObject(val) and val[part]?
+				val = val[part]
+			else
+				val = undefined
+				break
+		# Default.
 		if typeof val is "undefined"
 			return def
 		return val
 	# Returns a parameter message data.
 	# If the parameter is not present, an error is thrown.
 	getRequired: (param) ->
-		val = @data[param]
+		val = @getOptional param
 		if typeof val is "undefined"
 			throw new Error "Variable \"#{param}\" not found on message with address \"#{@address}\""
 		return val