简体   繁体   English

如何将字段列表动态添加到 GraphQL ObjectType

[英]How can I add a list of fields dynamically to GraphQL ObjectType

I have the following code:我有以下代码:

from starlette_graphene3 import GraphQLApp
import graphene

app = = APIRouter(
    dependencies=[Depends(auth_middleware)],
)

DYNAMIC_TYPES = {
    "length": graphene.Int(),
    "authors": graphene.List(of_type=str),
    "deprecated": graphene.String()
}

class MetaDataObject(graphene.ObjectType):
    resource_type = graphene.String()
    resource_name = graphene.String()

# I need to be able to do this somehow - specify a list of fieds and types dynamically.
for attr, g_type in DYNAMIC_TYPES.items():
    setattr(MetaDataObject, attr, g_type)


class Query(graphene.ObjectType):
    get_metadata = graphene.Field(MetaDataObject, resource_type=graphene.String(), resource_name=graphene.String())

    def resolve_get_metadata(self, info, resource_type, resource_name):

        response = table.get_item(
            Key={
                'resource_type': resource_type,
                'resource_name': resource_name
            }
        )

        if 'Item' not in response:
            return None

        return response['Item']


schema = graphene.Schema(query=Query, auto_camelcase=False)
app.add_route("/graphql", GraphQLApp(schema=schema))

As indicated above, I need to be able to specify a list of fieds and types dynamically and attach it to the Metadata Object. The issue is that the graphe.ObjectType is not a regular Python class, it has a special metaclass that takes care of some under-the-hood work, but I'm not sure how I can work with the Metaclass.如上所述,我需要能够动态指定字段和类型列表并将其附加到元数据 Object。问题是graphe.ObjectType不是常规的 Python class,它有一个特殊的元类来处理一些幕后工作,但我不确定如何使用元类。

You can create a graphene.Dynamic field in your MetaDataObject class, which can accept a list of fields and types as an argument.您可以在 MetaDataObject class 中创建一个 graphene.Dynamic 字段,它可以接受字段和类型列表作为参数。

You can use graphene.Field to define the fields, and graphene.List or graphene.NonNull to define the types of the fields.您可以使用graphene.Field来定义字段,使用graphene.Listgraphene.NonNull来定义字段的类型。

Like;喜欢;

class MetaDataObject(graphene.ObjectType):
    resource_type = graphene.String()
    resource_name = graphene.String()
    dynamic_fields = graphene.List(graphene.Field(graphene.String))

You can then pass the list of fields and types to the MetaDataObject class when you create an instance of it.然后,您可以在创建元数据对象 class 的实例时将字段和类型列表传递给它。

Like;喜欢;

metadata_object = MetaDataObject(dynamic_fields=[graphene.Field(graphene.String, name='field_name')])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM