|
| 1 | +from hashlib import sha1 |
| 2 | +from six import string_types |
| 3 | +from ..type import GraphQLSchema |
| 4 | + |
| 5 | +from .base import GraphQLBackend |
| 6 | + |
| 7 | +_cached_schemas = {} |
| 8 | + |
| 9 | +_cached_queries = {} |
| 10 | + |
| 11 | + |
| 12 | +def get_unique_schema_id(schema): |
| 13 | + """Get a unique id given a GraphQLSchema""" |
| 14 | + assert isinstance(schema, GraphQLSchema), ( |
| 15 | + "Must receive a GraphQLSchema as schema. Received {}" |
| 16 | + ).format(repr(schema)) |
| 17 | + |
| 18 | + if schema not in _cached_schemas: |
| 19 | + _cached_schemas[schema] = sha1(str(schema).encode("utf-8")).hexdigest() |
| 20 | + return _cached_schemas[schema] |
| 21 | + |
| 22 | + |
| 23 | +def get_unique_document_id(query_str): |
| 24 | + """Get a unique id given a query_string""" |
| 25 | + assert isinstance(query_str, string_types), ( |
| 26 | + "Must receive a string as query_str. Received {}" |
| 27 | + ).format(repr(query_str)) |
| 28 | + |
| 29 | + if query_str not in _cached_queries: |
| 30 | + _cached_queries[query_str] = sha1(str(query_str).encode("utf-8")).hexdigest() |
| 31 | + return _cached_queries[query_str] |
| 32 | + |
| 33 | + |
| 34 | +class GraphQLCachedBackend(GraphQLBackend): |
| 35 | + def __init__(self, backend, cache_map=None, use_consistent_hash=False): |
| 36 | + assert isinstance( |
| 37 | + backend, GraphQLBackend |
| 38 | + ), "Provided backend must be an instance of GraphQLBackend" |
| 39 | + if cache_map is None: |
| 40 | + cache_map = {} |
| 41 | + self.backend = backend |
| 42 | + self.cache_map = cache_map |
| 43 | + self.use_consistent_hash = use_consistent_hash |
| 44 | + |
| 45 | + def get_key_for_schema_and_document_string(self, schema, request_string): |
| 46 | + """This method returns a unique key given a schema and a request_string""" |
| 47 | + if self.use_consistent_hash: |
| 48 | + schema_id = get_unique_schema_id(schema) |
| 49 | + document_id = get_unique_document_id(request_string) |
| 50 | + return (schema_id, document_id) |
| 51 | + return hash((schema, request_string)) |
| 52 | + |
| 53 | + def document_from_string(self, schema, request_string): |
| 54 | + """This method returns a GraphQLQuery (from cache if present)""" |
| 55 | + key = self.get_key_for_schema_and_document_string(schema, request_string) |
| 56 | + if key not in self.cache_map: |
| 57 | + self.cache_map[key] = self.backend.document_from_string( |
| 58 | + schema, request_string |
| 59 | + ) |
| 60 | + |
| 61 | + return self.cache_map[key] |
0 commit comments