Add 'graphql' pview for authenticated users
authorLaurent Wouters <lwouters@cenotelie.fr>
Fri, 03 Apr 2020 10:26:07 +0200
changeset 10 b3037af67eab
parent 9 fa1f617f137e
child 11 d6b087e8c925
Add 'graphql' pview for authenticated users
cubicweb_graphql/__init__.py
cubicweb_graphql/views.py
--- a/cubicweb_graphql/__init__.py	Fri Dec 14 15:54:57 2018 +0100
+++ b/cubicweb_graphql/__init__.py	Fri Apr 03 10:26:07 2020 +0200
@@ -16,3 +16,8 @@
 # You should have received a copy of the GNU Lesser General Public License along
 # with CubicWeb.  If not, see <http://www.gnu.org/licenses/>.
 """Implementation of GraphQL support for CubicWeb"""
+
+
+def includeme(config):
+    config.add_route('graphql', '/graphql')
+    config.scan(__name__)
--- a/cubicweb_graphql/views.py	Fri Dec 14 15:54:57 2018 +0100
+++ b/cubicweb_graphql/views.py	Fri Apr 03 10:26:07 2020 +0200
@@ -17,7 +17,12 @@
 
 """cubicweb-graphql views/forms/actions/components for web ui"""
 
+import functools
+
 from cubicweb.web.views.ajaxcontroller import ajaxfunc
+from pyramid.httpexceptions import HTTPUnauthorized
+from pyramid.view import view_config
+
 from querier import GraphQLQuerier, format_execution_result
 
 
@@ -28,3 +33,26 @@
     results = GraphQLQuerier.execute(cnx, query)
     results = format_execution_result(results)
     return results
+
+
+def authenticated(func):
+    @functools.wraps(func)
+    def wrapped(request, *args):
+        if request.authenticated_userid is None:
+            raise HTTPUnauthorized()
+        return func(request, *args)
+
+    return wrapped
+
+
+@view_config(
+    route_name='graphql',
+    request_method='GET',
+    renderer='json',
+)
+@authenticated
+def graphql_pview(request):
+    query = request.params.get('query', '')
+    results = GraphQLQuerier.execute(request.cw_cnx, query)
+    results = format_execution_result(results)
+    return results