Ini*_*ood 3 python graphql strawberry-graphql
我想创建一个以字典作为参数的突变。有特定于实现的原因想要这样做,而不是为 dict 对象创建类型/模式。
# types.py
import typing
@strawberry.type
class Thing:
data: typing.Dict
Run Code Online (Sandbox Code Playgroud)
# resolvers.py
import typing
from .types import Thing
def create_config(data: typing.Dict) -> Thing:
pass
Run Code Online (Sandbox Code Playgroud)
# mutations.py
import strawberry
from .types import Thing
from .resolvers import create_thing
@strawberry.type
class Mutations:
create_thing: Thing = strawberry.mutation(resolver=create_thing)
Run Code Online (Sandbox Code Playgroud)
mutation {
createThing(data: {}) {}
}
Run Code Online (Sandbox Code Playgroud)
从阅读文档来看,没有与 dict 等效的 GraphQL 标量。当我尝试测试时,这个编译错误证明了这一点:
TypeError: Thing fields cannot be resolved. Unexpected type 'typing.Dict'
我的本能是将 dict 扁平化为 JSON 字符串并以这种方式传递。这看起来不优雅,这让我认为有一种更惯用的方法。我应该从这里去哪里?
JSON 本身可以是标量,而不是序列化的 JSON 字符串。
from strawberry.scalars import JSON
@strawberry.type
class Thing:
data: JSON
def create_config(data: JSON) -> Thing:
pass
Run Code Online (Sandbox Code Playgroud)