Implement a encoded search to json-ld wrapper.
[htsworkflow.git] / htsworkflow / submission / encoded.py
index 507271355988db469a83cb34560c8fb15cabaf93..1228d387f015a39a9da12c8ad5ca296d218c68de 100644 (file)
@@ -109,7 +109,7 @@ class ENCODED:
             self.username = authenticators[0]
             self.password = authenticators[2]
 
-    def add_jsonld_context(self, tree, contexts, base):
+    def add_jsonld_context(self, tree, default_base):
         """Add contexts to various objects in the tree.
 
         tree is a json tree returned from the DCC's encoded database.
@@ -118,11 +118,10 @@ class ENCODED:
         base, if supplied allows setting the base url that relative
             urls will be resolved against.
         """
-        tree['@context'] = contexts[None]
-        tree['@context']['@base'] = base
-        self.add_jsonld_child_context(tree, contexts)
+        self.add_jsonld_child_context(tree, default_base)
+        self.add_jsonld_namespaces(tree['@context'])
 
-    def add_jsonld_child_context(self, obj, contexts):
+    def add_jsonld_child_context(self, obj, default_base):
         '''Add JSON-LD context to the encoded JSON.
 
         This is recursive because some of the IDs were relative URLs
@@ -205,7 +204,7 @@ class ENCODED:
         '''
         url = self.prepare_url(obj_id)
         json = self.get_json(obj_id, **kwargs)
-        self.add_jsonld_context(json, self.context, url)
+        self.add_jsonld_context(json, url)
         return json
 
     def get_object_type(self, obj):
@@ -218,7 +217,7 @@ class ENCODED:
     def get_schema_url(self, obj):
         obj_type = self.get_object_type(obj)
         if obj_type:
-            return self.prepare_url(ENCODED_SCHEMA_ROOT + obj_type + '.json')
+            return self.prepare_url(ENCODED_SCHEMA_ROOT + obj_type + '.json') + '#'
 
     def _is_encoded_object(self, obj):
         '''Test to see if an object is a JSON-LD object
@@ -278,6 +277,28 @@ class ENCODED:
         url = urlunparse(url.values())
         return url
 
+    def search_jsonld(self, term, **kwargs):
+        '''Send search request to ENCODED
+        '''
+        url = self.prepare_url('/search/')
+        result = self.get_json(url, searchTerm=term, **kwargs)
+        self.convert_search_to_jsonld(result)
+        return result
+
+    def convert_search_to_jsonld(self, result):
+        '''Add the context to search result
+
+        Also remove hard to handle nested attributes
+          e.g. remove object.term when we have no id
+        '''
+        graph = result['@graph']
+        for i, obj in enumerate(graph):
+            # suppress nested attributes
+            graph[i] = {k: v for k, v in obj.items() if '.' not in k}
+
+        self.add_jsonld_context(result, self.prepare_url(result['@id']))
+        return result
+
     def validate(self, obj):
         obj_type = self.get_object_type(obj)
         schema_url = self.get_schema_url(obj)