square / fdoc

Documentation format and verification
Other
379 stars 59 forks source link

Dynamic keys? #54

Closed subdigital closed 10 years ago

subdigital commented 10 years ago

I have a json response that includes a couple of objects that serve as lookups for the main response fragment:

Example:

{
   "books": [
       {
            "id":  12,
            "name": "book1",
            "author_id": 1
       },
       {
            "id": 125,
            "name": "book125",
            "author_id": 4
       }
   ],
   "authors": {
       "1": { ....},
       "4": {.....}
   }
}

Instead of authors being an array, it's instead an object the author id as the key. This makes it really easy for clients to parse into their native data structures (Dictionary, Hash, whatever) and do quick lookups when building up the response objects.

The main reason is that there might be a ton of books by the same author and this severely cuts down in the overall response size by eliminating the duplication.

Now when I bring fdoc in, it fails because I don't really have a way to describe this structure.

I'm thinking of something like this:

   authors:
          description: A lookup of the authors represented in the book list.
          required: false
          type: object
          properties:
            __id__:
              property_type: dynamic 
              type: object
              properties:
                id:
                  description: the id of the author
                  type: integer
                  example: 24512

Here the __id__ is perhaps a convention that this property is special, and the property_type attribute set to dynamic could tell the validator to not just treat the attribute at face value.

If this is not currently possible to validate with fdoc, I'd love to know. Failing that is there a way to ignore an entire fragment (but validate the rest) so that my tests don't fail for these endpoints?

zachmargolis commented 10 years ago

So fdoc actually uses on JSON schema (http://json-schema.org/latest/json-schema-core.html) for the actual schema description. To my knowledge there is no way in JSON schema to do what you're describing.

From my personal experience, using arrays for these kinds of things is straightforward and works in more places. It's pretty easy to build a dictionary/hash out of objects client-side once you have them loaded anyways.

{
  "authors": [
    { "id": 1 },
    { "id": 4 }
  ]
}

Since JSON schema doesn't do this, I'm not sure this is something fdoc is going to handle now.

subdigital commented 10 years ago

Thanks for the quick response. I figured the change would have to be supported by json-schema, and in looking at their code I'm not sure how I'd even add it in. Sadly that I may have to give up on fdoc if I want this style of response (but I may just end up making it an array like you suggest).