toddmohney / json-api

Haskell Implementation of the JSON-API specification
http://hackage.haskell.org/package/json-api
MIT License
35 stars 14 forks source link

Document structure differs if there's only one item in the list #38

Closed eahlberg closed 4 years ago

eahlberg commented 4 years ago

Hey @toddmohney. First off, thanks for a nice lib! 🙏

An issue I've came across is that if I pass a list with a single item to mkDocument, i.e. mkDocument [x] Nothing Nothing (where x is an instance of ResourcefulEntity), the resulting JSON is:

{
  "data": {
    "attributes": {
      "id": 1,
      "title": "How to write a JSON API"
     }
  },
   ...fields omitted
}

However, if I pass a list of items to mkDocument, i.e. mkDocument [x1, x2] Nothing Nothing, data is now an array in the response:

{
  "data": [
    {
      "attributes": {
        "id": 1,
        "title": "How to write a JSON API in Haskell"
       }
    },
    {
      "attributes": {
        "id": 2,
        "title": "Why JSON:API?"
     }
     }
   ],
   ...fields omitted
}

Is it possible to specify that I'd like to return a list even though there's only one item in the list?

I've looked at the source code, and I believe it is this case that I'm talking about. I'm a bit unsure if the behavior is well specified in the JSON:API specification or not, but I took a look at the jsonapiplayground and it seems that a list with a single item has the same structure as a list with a multiple items, e.g. list with a single item, list with multiple items.

eahlberg commented 4 years ago

False alarm! I figured out how to accomplish what I want. For future readers, you can do it as follows:

  1. Convert instances of ResourcefulEntity to ResourceData using list
  2. Use the ResourceData variant for creating the document, i.e. this