1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
|
from typing import NamedTuple
from graphql import (
graphql_sync,
print_schema,
GraphQLField,
GraphQLObjectType,
GraphQLResolveInfo,
GraphQLSchema,
GraphQLString,
)
from graphql_relay import plural_identifying_root_field
from ..utils import dedent
user_type = GraphQLObjectType(
"User",
fields=lambda: {
"username": GraphQLField(GraphQLString),
"url": GraphQLField(GraphQLString),
},
)
class User(NamedTuple):
username: str
url: str
def resolve_single_input(info: GraphQLResolveInfo, username: str) -> User:
assert info.schema is schema
lang = info.context.lang
url = f"www.facebook.com/{username}?lang={lang}"
return User(username=username, url=url)
query_type = GraphQLObjectType(
"Query",
lambda: {
"usernames": plural_identifying_root_field(
"usernames",
description="Map from a username to the user",
input_type=GraphQLString,
output_type=user_type,
resolve_single_input=resolve_single_input,
)
},
)
schema = GraphQLSchema(query=query_type)
class Context(NamedTuple):
lang: str
def describe_plural_identifying_root_field():
def allows_fetching():
source = """
{
usernames(usernames:["dschafer", "leebyron", "schrockn"]) {
username
url
}
}
"""
context_value = Context(lang="en")
assert graphql_sync(schema, source, context_value=context_value) == (
{
"usernames": [
{
"username": "dschafer",
"url": "www.facebook.com/dschafer?lang=en",
},
{
"username": "leebyron",
"url": "www.facebook.com/leebyron?lang=en",
},
{
"username": "schrockn",
"url": "www.facebook.com/schrockn?lang=en",
},
]
},
None,
)
def generates_correct_types():
assert print_schema(schema) == dedent(
'''
type Query {
"""Map from a username to the user"""
usernames(usernames: [String!]!): [User]
}
type User {
username: String
url: String
}
'''
)
|