forked from OCA/rest-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
24 changed files
with
469 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
this file will be generated after merging |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
# Copyright 2018 ACSONE SA/NV | ||
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). | ||
|
||
from .controllers import GraphQLControllerMixin | ||
from .types import OdooObjectType |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
# Copyright 2018 ACSONE SA/NV | ||
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). | ||
|
||
{ | ||
"name": "Graphql Base", | ||
"summary": """ | ||
Base GraphQL/GraphiQL controller""", | ||
"version": "12.0.1.0.0", | ||
"license": "LGPL-3", | ||
"author": "ACSONE SA/NV,Odoo Community Association (OCA)", | ||
"website": "https://github.com/OCA/rest-framework", | ||
"depends": ["base"], | ||
"data": ["views/graphiql.xml"], | ||
"external_dependencies": {"python": ["graphene", "graphql_server"]}, | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
from .main import GraphQLControllerMixin |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,84 @@ | ||
# Copyright 2018 ACSONE SA/NV | ||
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). | ||
|
||
import re | ||
from functools import partial | ||
|
||
from graphql_server import ( | ||
default_format_error, | ||
encode_execution_results, | ||
json_encode, | ||
load_json_body, | ||
run_http_query, | ||
) | ||
|
||
from odoo import http | ||
|
||
|
||
class GraphQLControllerMixin(object): | ||
@staticmethod | ||
def patch_for_json(path_re): | ||
# this is to avoid Odoo, which assumes json always means json+rpc, | ||
# complaining about "function declared as capable of handling request | ||
# of type 'http' but called with a request of type 'json'" | ||
path_re = re.compile(path_re) | ||
orig_get_request = http.Root.get_request | ||
|
||
def get_request(self, httprequest): | ||
if path_re.match(httprequest.path): | ||
return http.HttpRequest(httprequest) | ||
return orig_get_request(self, httprequest) | ||
|
||
http.Root.get_request = get_request | ||
|
||
def _parse_body(self): | ||
req = http.request.httprequest | ||
# We use mimetype here since we don't need the other | ||
# information provided by content_type | ||
content_type = req.mimetype | ||
if content_type == "application/graphql": | ||
return {"query": req.data.decode("utf8")} | ||
elif content_type == "application/json": | ||
return load_json_body(req.data.decode("utf8")) | ||
elif content_type in ( | ||
"application/x-www-form-urlencoded", | ||
"multipart/form-data", | ||
): | ||
return http.request.params | ||
return {} | ||
|
||
def _process_request(self, schema, data, catch): | ||
request = http.request.httprequest | ||
execution_results, all_params = run_http_query( | ||
schema, | ||
request.method.lower(), | ||
data, | ||
query_data=request.args, | ||
batch_enabled=False, | ||
catch=catch, | ||
context={"env": http.request.env}, | ||
) | ||
result, status_code = encode_execution_results( | ||
execution_results, | ||
is_batch=isinstance(data, list), | ||
format_error=default_format_error, | ||
encode=partial(json_encode, pretty=False), | ||
) | ||
# TODO what to do with status_code? | ||
return http.request.make_response( | ||
result, headers={"Content-Type": "application/json"} | ||
) | ||
|
||
def _handle_graphql_request(self, schema): | ||
data = self._parse_body() | ||
return self._process_request(schema, data, catch=False) | ||
|
||
def _handle_graphiql_request(self, schema): | ||
req = http.request.httprequest | ||
if req.method == "GET" and req.accept_mimetypes.accept_html: | ||
return http.request.render("graphql_base.graphiql", {}) | ||
# this way of passing a GraphQL query over http is not spec compliant | ||
# (https://graphql.org/learn/serving-over-http/), but we use | ||
# this only for our GraphiQL UI, and it works with Odoo's way | ||
# of passing the csrf token | ||
return self._process_request(schema, http.request.params, catch=True) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
# Translation of Odoo Server. | ||
# This file contains the translation of the following modules: | ||
# | ||
msgid "" | ||
msgstr "" | ||
"Project-Id-Version: Odoo Server 12.0+e\n" | ||
"Report-Msgid-Bugs-To: \n" | ||
"Last-Translator: <>\n" | ||
"Language-Team: \n" | ||
"MIME-Version: 1.0\n" | ||
"Content-Type: text/plain; charset=UTF-8\n" | ||
"Content-Transfer-Encoding: \n" | ||
"Plural-Forms: \n" | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
This modules enables the creation of `GraphQL <https://graphql.org/>`_ endpoints. | ||
In itself, it does nothing and must be used by a developer to | ||
create the GraphQL schema and resolvers using | ||
`graphene <https://graphene-python.org/>`_, | ||
and expose them through a controller. | ||
An example is available in the ``graphql_demo`` module. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
To use this module, you need to | ||
|
||
- create your graphene schema | ||
- create your controller to expose your GraphQL endpoint, | ||
and optionally a GraphiQL UI. | ||
|
||
This module does not attempt to expose the whole Odoo object model. | ||
This could be the purpose of another module based on this one. | ||
We believe however that it is preferable to expose a specific well tested | ||
endpoint for each customer, so as to reduce coupling by knowing precisely | ||
what is exposed and needs to be tested when upgrading Odoo. |
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
# Copyright 2018 ACSONE SA/NV | ||
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). | ||
|
||
import graphene | ||
|
||
from odoo import fields | ||
|
||
|
||
def odoo_attr_resolver(attname, default_value, root, info, **args): | ||
"""An attr resolver that is specialized for Odoo recordsets. | ||
It converts False to None, except for Odoo Boolean fields. | ||
This is necessary because Odoo null values are often represented | ||
as False, and graphene would convert a String field with value False | ||
to "false". | ||
It converts datetimes to the user timezone. | ||
It also raises an error if the attribute is not present, ignoring | ||
any default value, so as to return if the schema declares a field | ||
that is not present in the underlying Odoo model. | ||
""" | ||
value = getattr(root, attname) | ||
field = root._fields.get(attname) | ||
if value is False: | ||
if not isinstance(field, fields.Boolean): | ||
return None | ||
elif isinstance(field, fields.Datetime): | ||
return fields.Datetime.context_timestamp(root, value) | ||
return value | ||
|
||
|
||
class OdooObjectType(graphene.ObjectType): | ||
"""A graphene ObjectType with an Odoo aware default resolver.""" | ||
|
||
@classmethod | ||
def __init_subclass_with_meta__(cls, default_resolver=None, **options): | ||
if default_resolver is None: | ||
default_resolver = odoo_attr_resolver | ||
|
||
return super(OdooObjectType, cls).__init_subclass_with_meta__( | ||
default_resolver=default_resolver, **options | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,153 @@ | ||
<?xml version="1.0" encoding="utf-8"?> | ||
<!-- | ||
Copyright 2018 ACSONE SA/NV | ||
License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). | ||
The html code below is originally Copyright (c) Facebook, Inc. | ||
published under Apache license. | ||
--> | ||
<odoo> | ||
<template id="graphiql" name="GraphiQL"> | ||
<t t-call="web.layout"> | ||
<t t-set="head"> | ||
<style> | ||
body { | ||
height: 100%; | ||
margin: 0; | ||
width: 100%; | ||
overflow: hidden; | ||
} | ||
#graphiql { | ||
height: 100vh; | ||
} | ||
</style> | ||
|
||
<!-- | ||
This GraphiQL example depends on Promise and fetch, which are available in | ||
modern browsers, but can be "polyfilled" for older browsers. | ||
GraphiQL itself depends on React DOM. | ||
If you do not want to rely on a CDN, you can host these files locally or | ||
include them directly in your favored resource bunder. | ||
--> | ||
<link href="//cdn.jsdelivr.net/npm/[email protected]/graphiql.css" rel="stylesheet"/> | ||
<script src="//cdn.jsdelivr.net/npm/[email protected]/fetch.min.js"></script> | ||
<script src="//cdn.jsdelivr.net/npm/[email protected]/umd/react.production.min.js"></script> | ||
<script src="//cdn.jsdelivr.net/npm/[email protected]/umd/react-dom.production.min.js"></script> | ||
<script src="//cdn.jsdelivr.net/npm/[email protected]/graphiql.min.js"></script> | ||
</t> | ||
<t t-set="head" t-value="head"/> | ||
</t> | ||
<body> | ||
<div id="graphiql">Loading...</div> | ||
<script> | ||
|
||
/** | ||
* This GraphiQL example illustrates how to use some of GraphiQL's props | ||
* in order to enable reading and updating the URL parameters, making | ||
* link sharing of queries a little bit easier. | ||
* | ||
* This is only one example of this kind of feature, GraphiQL exposes | ||
* various React params to enable interesting integrations. | ||
*/ | ||
|
||
// Parse the search string to get url parameters. | ||
var search = window.location.search; | ||
var parameters = {}; | ||
search.substr(1).split('&').forEach(function (entry) { | ||
var eq = entry.indexOf('='); | ||
if (eq >= 0) { | ||
parameters[decodeURIComponent(entry.slice(0, eq))] = | ||
decodeURIComponent(entry.slice(eq + 1)); | ||
} | ||
}); | ||
|
||
// if variables was provided, try to format it. | ||
if (parameters.variables) { | ||
try { | ||
parameters.variables = | ||
JSON.stringify(JSON.parse(parameters.variables), null, 2); | ||
} catch (e) { | ||
// Do nothing, we want to display the invalid JSON as a string, rather | ||
// than present an error. | ||
} | ||
} | ||
|
||
// When the query and variables string is edited, update the URL bar so | ||
// that it can be easily shared | ||
function onEditQuery(newQuery) { | ||
parameters.query = newQuery; | ||
updateURL(); | ||
} | ||
|
||
function onEditVariables(newVariables) { | ||
parameters.variables = newVariables; | ||
updateURL(); | ||
} | ||
|
||
function onEditOperationName(newOperationName) { | ||
parameters.operationName = newOperationName; | ||
updateURL(); | ||
} | ||
|
||
function updateURL() { | ||
var newSearch = '?' + Object.keys(parameters).filter(function (key) { | ||
return Boolean(parameters[key]); | ||
}).map(function (key) { | ||
return encodeURIComponent(key) + '=' + | ||
encodeURIComponent(parameters[key]); | ||
}).join('&'); | ||
history.replaceState(null, null, newSearch); | ||
} | ||
|
||
// Defines a GraphQL fetcher using the fetch API. You're not required to | ||
// use fetch, and could instead implement graphQLFetcher however you like, | ||
// as long as it returns a Promise or Observable. | ||
function graphQLFetcher(graphQLParams) { | ||
// This example expects a GraphQL server at the path /graphql. | ||
// Change this to point wherever you host your GraphQL server. | ||
data = new FormData(); | ||
data.append('query', graphQLParams['query']); | ||
if (graphQLParams['variables']) { | ||
data.append('variables', JSON.stringify(graphQLParams['variables'])); | ||
} | ||
if (graphQLParams['operationName']) { | ||
data.append('operationName', graphQLParams['operationName']); | ||
} | ||
data.append('csrf_token', odoo.csrf_token); | ||
return fetch('', { | ||
method: 'post', | ||
headers: { | ||
'Accept': 'application/json', | ||
}, | ||
body: data, | ||
credentials: 'include', | ||
}).then(function (response) { | ||
return response.text(); | ||
}).then(function (responseBody) { | ||
try { | ||
return JSON.parse(responseBody); | ||
} catch (error) { | ||
return responseBody; | ||
} | ||
}); | ||
} | ||
|
||
// Render <GraphiQL /> into the body. | ||
// See the README in the top level of this module to learn more about | ||
// how you can customize GraphiQL by providing different values or | ||
// additional child elements. | ||
ReactDOM.render( | ||
React.createElement(GraphiQL, { | ||
fetcher: graphQLFetcher, | ||
query: parameters.query, | ||
variables: parameters.variables, | ||
operationName: parameters.operationName, | ||
onEditQuery: onEditQuery, | ||
onEditVariables: onEditVariables, | ||
onEditOperationName: onEditOperationName | ||
}), | ||
document.getElementById('graphiql') | ||
); | ||
</script> | ||
</body> | ||
</template> | ||
</odoo> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
this file will be generated after merging |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
from . import controllers |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
# Copyright 2018 ACSONE SA/NV | ||
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). | ||
|
||
{ | ||
"name": "GraphQL Demo", | ||
"description": """ | ||
GraphQL demo module""", | ||
"version": "12.0.1.0.0", | ||
"license": "LGPL-3", | ||
"author": "ACSONE SA/NV, Odoo Community Association (OCA)", | ||
"website": "https://github.com/OCA/rest-framework", | ||
"depends": ["graphql_base"], | ||
"external_dependencies": {"python": ["graphene"]}, | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
from . import main |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
# Copyright 2018 ACSONE SA/NV | ||
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). | ||
|
||
from odoo import http | ||
from odoo.addons.graphql_base import GraphQLControllerMixin | ||
|
||
from ..schema import schema | ||
|
||
GRAPHIQL_PATH = "/graphiql/demo" | ||
GRAPHQL_PATH = "/graphql/demo" | ||
|
||
GraphQLControllerMixin.patch_for_json("^" + GRAPHQL_PATH + "/?$") | ||
|
||
|
||
class GraphQLController(http.Controller, GraphQLControllerMixin): | ||
@http.route(GRAPHIQL_PATH, auth="user") | ||
def graphiql(self, **kwargs): | ||
return self._handle_graphiql_request(schema) | ||
|
||
@http.route(GRAPHQL_PATH, auth="api_key", csrf=False) | ||
def graphql(self, **kwargs): | ||
return self._handle_graphql_request(schema) |
Oops, something went wrong.