Skip to content

Commit 2abe5d1

Browse files
committed
Add default cached graphql query parser
1 parent 1cc4308 commit 2abe5d1

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

aiohttp_graphql/graphqlview.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
from collections import Mapping
2-
from functools import partial
2+
from functools import partial, lru_cache
33

44
from aiohttp import web
55
from promise import Promise
66

7+
from graphql import Source, parse, validate
78
from graphql.type.schema import GraphQLSchema
89
from graphql.execution.executors.asyncio import AsyncioExecutor
910
from graphql_server import (
@@ -33,6 +34,7 @@ def __init__(
3334
batch=False,
3435
jinja_env=None,
3536
max_age=86400,
37+
max_cached_queries=128,
3638
encoder=None,
3739
error_formatter=None,
3840
enable_async=True,
@@ -52,6 +54,7 @@ def __init__(
5254
self.batch = batch
5355
self.jinja_env = jinja_env
5456
self.max_age = max_age
57+
self.parser = self.get_cached_parser(max_cached_queries)
5558
self.encoder = encoder or json_encode
5659
self.error_formatter = error_formatter or default_format_error
5760
self.enable_async = enable_async and isinstance(
@@ -91,6 +94,16 @@ async def parse_body(self, request):
9194

9295
return {}
9396

97+
@staticmethod
98+
def get_cached_parser(max_cached_queries):
99+
@lru_cache(maxsize=max_cached_queries)
100+
def cached_parser(query, schema):
101+
source = Source(query, name='GraphQL request')
102+
ast = parse(source)
103+
validation_errors = validate(schema, ast)
104+
return ast, validation_errors
105+
return cached_parser
106+
94107
def render_graphiql(self, params, result):
95108
return render_graphiql(
96109
jinja_env=self.jinja_env,
@@ -140,7 +153,8 @@ async def __call__(self, request):
140153
root_value=self.root_value,
141154
context_value=self.get_context(request),
142155
middleware=self.middleware,
143-
executor=self.executor,
156+
parser=self.parser,
157+
executor=self.executor
144158
)
145159

146160
awaited_execution_results = await Promise.all(execution_results)

0 commit comments

Comments
 (0)