Skip to content

Instantly share code, notes, and snippets.

@Speedy1991
Last active November 4, 2021 12:09
Show Gist options
  • Save Speedy1991/ef31bd710d28f43c61e8c3efec613bf0 to your computer and use it in GitHub Desktop.
Save Speedy1991/ef31bd710d28f43c61e8c3efec613bf0 to your computer and use it in GitHub Desktop.
Track deprecated stawberry graphql fields with elasticsearch
from strawberry.extensions import Extension
from strawberry.types import Info
class TrackDeprecatedFieldsExtension(Extension):
def __init__(self, *args, callback: Callable[[Dict[str, int]], None], single_count=True, **kwargs):
"""
:param callback: Callback which is called with the deprecated fields dictionary
:param single_count: If true only count once per request, otherwise count once per field call
"""
super().__init__(*args, **kwargs)
self.deprecated_fields = dict()
self.callback = callback
self.single_count = single_count
def on_request_end(self):
if self.deprecated_fields:
self.callback(self.deprecated_fields)
def resolve(self, _next, root, info: Info, *args, **kwargs):
field_name = info.field_name
try:
is_deprecated = info.parent_type.fields[field_name].is_deprecated
if is_deprecated:
key = f'{info.parent_type.name}.{field_name}'
if self.single_count:
self.deprecated_fields[key] = 1
else:
self.deprecated_fields[key] = self.deprecated_fields.get(key, 0) + 1
except KeyError:
pass
return _next(root, info, *args, **kwargs)
from elasticsearch import Elasticsearch
import strawberry
# Just an example, for performance reason you should send this to an async queue/task, e.g.:
# from django_q.tasks import async_task
# send_to_elasticsearch = lambda payload: async_task('schedule.index_es', {'index': 'deprecated_graphql_fields.v1', doc: {**payload, "schema": "myschemaname"}})
def send_to_elasticsearch(payload):
es = Elasticsearch(['https://myelasticsearchendpoint.com'], http_auth=('username', 'password'))
doc = {
**payload,
"schema": "myschemaname"
}
es.index('deprecated_graphql_fields.v1', body=doc)
es.close()
schema = strawberry.Schema(query=Query, mutation=Mutation, extensions=[lambda *args, **kwargs: TrackDeprecatedFieldsExtension(*args, callback=send_to_elasticsearch, **kwargs)])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment