diff --git a/confluent/httpapi.py b/confluent/httpapi.py index 3274deca..ab6774c7 100644 --- a/confluent/httpapi.py +++ b/confluent/httpapi.py @@ -8,6 +8,7 @@ import Cookie import confluent.auth as auth import confluent.consoleserver as consoleserver import confluent.exceptions as exc +import confluent.messages import confluent.pluginapi as pluginapi import confluent.util as util import eventlet @@ -262,15 +263,52 @@ def _assemble_html(responses, resource, querydict): def _assemble_json(responses, resource): - yield '[' docomma = False + links = { + 'self': ['{"href"="%s"' % resource], + 'collection': ['{"href"="%s"' % '../'], + } + yield '{' + hadrsp = False for rsp in responses: + if isinstance(rsp, confluent.messages.LinkRelation): + haldata = rsp.json_hal() + for hk in haldata.iterkeys(): + if hk in links: + links[hk].append(haldata[hk]) + else: + links[hk] = [haldata[hk]] + continue + hadrsp = True if docomma: yield ',' else: docomma = True yield rsp.json() - yield ']' + docomma = False + if hadrsp: + yield ',' + yield '"_links": {' + groupcomma = False + for link in links.iterkeys(): + if groupcomma: + yield ',' + else: + groupcomma = True + yield json.dumps(link) + ":" + if len(links[link]) == 1: + yield links[link][0] + else: + yield '[' + for lk in links[link]: + if docomma: + yield ',' + else: + docomma = True + yield lk + yield ']' + yield '}' + yield '}' def serve(): diff --git a/confluent/messages.py b/confluent/messages.py index 97f24ab6..0bce04dc 100644 --- a/confluent/messages.py +++ b/confluent/messages.py @@ -15,7 +15,8 @@ class ConfluentMessage(object): def json(self): # This will create the canonical json representation of this message - return json.dumps(self.kvpairs, separators=(',', ':')) + jsonsnippet = json.dumps(self.kvpairs, separators=(',', ':'))[1:-1] + return jsonsnippet def strip_node(self, node): self.kvpairs = self.kvpairs[node] @@ -61,6 +62,9 @@ class ConfluentChoiceMessage(ConfluentMessage): return snippet class LinkRelation(ConfluentMessage): + def json_hal(self): + return {self.rel: '{ "href": "%s" }' % self.href } + def html(self): return '%s' % (self.href, self.rel, self.href)