Skip to content

Instantly share code, notes, and snippets.

@netmilk
Last active December 15, 2015 00:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save netmilk/11b7a9f7bbe5a9ada3e2 to your computer and use it in GitHub Desktop.
Save netmilk/11b7a9f7bbe5a9ada3e2 to your computer and use it in GitHub Desktop.
Workaround for nullable MSON attributes in Dredd Ruby and Node.js hooks
# My API
# My Resource [/my_resource]
# Its Action [GET]
+ Response 200 (application/json)
+ Attributes (My Structure)
# Data Structures
## My Structure (object)
- myKey: myValue (string)
- destination: (object, nullable, optional) - Some description #nullable
- someObject: (object)
- itsKey: (string, nullable, optional) - Some other description #nullable
require 'json'
include DreddHooks::Methods
# Recursively add null as acceptable type if there is string
# "#nullable" present in the property description
def patch_properties_with_nullable schema
if !schema['description'].nil?
if schema['description'].include? "#nullable"
if schema['type'].nil?
schema['type'] = 'null'
elsif schema['type'].is_a? String
schema['type'] = [schema['type'], 'null']
elsif schema['type'].is_a? Array
schema['type'].push 'null'
end
end
end
if schema['properties'].is_a? Hash
schema['properties'].each do |key, value|
schema['properties'][key] = patch_properties_with_nullable value
end
end
schema
end
before_all do |transactions|
transactions.each_with_index do |transaction, index|
if ! transaction['expected']['bodySchema'].nil?
schema = JSON.parse transaction['expected']['bodySchema']
schema = patch_properties_with_nullable schema
transactions[index]['expected']['bodySchema'] = schema.to_json
end
end
end
#!/bin/sh
dredd apiary.apib http://localhost:3000 --hookfiles=./hooks.rb --language ruby
{
"type":"object",
"properties":{
"myKey":{
"type":"string"
},
"destination":{
"type":[
"object",
"null"
],
"description":"Some description #nullable"
},
"someObject":{
"type":"object",
"properties":{
"itsKey":{
"type":[
"string",
"null"
],
"description":"Some other description #nullable"
}
}
}
},
"$schema":"http://json-schema.org/draft-04/schema#"
}
{
"type": "object",
"properties": {
"myKey": {
"type": "string"
},
"destination": {
"type": "object",
"description": "Some description #nullable"
},
"someObject": {
"type": "object",
"properties": {
"itsKey": {
"type": "string",
"description": "Some other description #nullable"
}
}
}
},
"$schema": "http://json-schema.org/draft-04/schema#"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment