Skip to content

Instantly share code, notes, and snippets.

@matthewwithanm
Created April 21, 2012 14:57
Show Gist options
  • Save matthewwithanm/2437548 to your computer and use it in GitHub Desktop.
Save matthewwithanm/2437548 to your computer and use it in GitHub Desktop.
Difficulties with JSON Association Technique
// 1. Relying on pluralization can be tricky.
var payload = {
"deer": {
"id": 1,
"name": "Bambi",
"related_deer": [1, 2, 3]
},
"deerses": [ // ????
{"id": 2, ...},
{"id": 3, ...}
]
};
// 2. Getting result object requires knowing requested type.
// 3. Method of accessing the result is different for every type.
doSomethingWithPayload(payload); // Oops. doSomethingWithResult needs to know that "deer" is the special key for this payload.
// 4. Related object lookups require special logic for requested type.
var relatedDeer = payload.deerses.filter(function(o) { return payload.deer.related_deer.indexOf(o.id) !== -1; }); // Oops! Won't work because Bambi isn't in deerses list.
// 5. The solution can't be extrapolated for collections. (We can't use the plural key because there'd be no way to differentiate between results and objects related to results. Keeping the results and related objects under different keys just exacerbates issue 4.)
var payload = {
"deerses": [ // Which match our request?
{"id": 2, ...},
{"id": 3, ...}
]
};
@wycats
Copy link

wycats commented Apr 21, 2012

Maybe the right answer is:

var payload = {
  "record": {
    "id": 1,
    "name": "Bambi",
    "related_deer": [1, 2, 3]
  },
  "other": {
    { "deer": [
      {"id": 2, ...},
      {"id": 3, ...}
    ]
  }
};

@matthewwithanm
Copy link
Author

Yeah, that definitely solves the first three points. To solve 4 and 5, I think something more relational is needed. As an example:

var payload = {
  "result": {"type": "deer", "key": "1"},
  "records": {
    "deer": {
      "1": {
        "id": 1,
        "name": "Bambi",
        "related_deer": [1, 2, 3]
      },
      "2": {"id": 2, ...},
      "3": {"id": 3, ...}
    }
  }
};

Now we can do something like this:

var result = payload.records[payload.result.type][payload.result.key]
var relatedDeer = _.values(payload.records.deer).filter(function(o) { return result.related_deer.indexOf(o.id) !== -1; });

I'm not terribly fond of the means of referencing a record. Maybe just a list of ids would be better (but that would reintroduce issues 2 and 3).

Centralizing the records also has the benefit of an obvious extrapolation to collections: "result" (or "results") would simply be a list of references.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment