From 5591be7ecd5e87d05f4d610270887deca45c41e2 Mon Sep 17 00:00:00 2001 From: Isaac Parker Date: Sat, 16 Dec 2023 23:08:30 -0700 Subject: [PATCH] hack: try out some gql annotation ideas --- gifter/graphql.py | 67 ++++++++++++++++++++++++++++++++++++++++++ gifter/models.py | 15 +++++++++- gifter/test_graphql.py | 7 +++++ 3 files changed, 88 insertions(+), 1 deletion(-) create mode 100755 gifter/graphql.py create mode 100644 gifter/test_graphql.py diff --git a/gifter/graphql.py b/gifter/graphql.py new file mode 100755 index 0000000..b710d43 --- /dev/null +++ b/gifter/graphql.py @@ -0,0 +1,67 @@ +from . import models + +import inspect, sys +from pprint import pprint + +schema = {} + + +class String: + pass + + +class Int: + pass + + +class UUID: + pass + + +class JSON: + pass + + +class DateTime: + pass + + +class Boolean: + pass + + +for name, obj in inspect.getmembers(sys.modules[models.__name__]): + if inspect.isclass(obj): + if hasattr(obj, "_meta") and not obj._meta.abstract: + if not hasattr(obj, 'GQLMeta'): + continue + + obj_gql_name = f"{obj.__name__}Type" + schema[obj_gql_name] = {} + fields = obj._meta.fields + for field in fields: + + if not hasattr(field, "__graphql_enabled"): + continue + + match field.get_internal_type(): + case "CharField" | "TextField": + schema[obj_gql_name][field.name] = String + case "IntegerField": + schema[obj_gql_name][field.name] = Int + case "UUIDField": + schema[obj_gql_name][field.name] = UUID + case "JSONField": + schema[obj_gql_name][field.name] = JSON + case "DateTimeField": + schema[obj_gql_name][field.name] = DateTime + case "BooleanField": + schema[obj_gql_name][field.name] = Boolean + case "ForeignKey" | "AutoField": + pprint(field) + case _: + raise Exception(f"Unknown field type: {field.get_internal_type()}") + + +def foo(): + pprint(schema) diff --git a/gifter/models.py b/gifter/models.py index 18957d8..4feb586 100644 --- a/gifter/models.py +++ b/gifter/models.py @@ -1,4 +1,6 @@ import hashlib +from dataclasses import dataclass +from typing import Any import uuid import secrets @@ -84,8 +86,19 @@ def __str__(self): return self.display_name +def with_graphql(field): + setattr(field, "__graphql_enabled", True) + return field + + class Wishlist(CommonBaseClass): - title = models.CharField(max_length=120, blank=False, null=False) + + @dataclass + class GQLMeta: + enabled = True + auth_check_via = "groups" + + title = with_graphql(models.CharField(max_length=120, blank=False, null=False)) owner = models.ForeignKey(User, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) diff --git a/gifter/test_graphql.py b/gifter/test_graphql.py new file mode 100644 index 0000000..f4fb3a4 --- /dev/null +++ b/gifter/test_graphql.py @@ -0,0 +1,7 @@ +from django.test import TestCase +from . import graphql + +class TestGraphql(TestCase): + + def test_graphql(self): + graphql.foo()