def get_schema(self): self.query.field("_service")(self._query_service_resolver) if self.federated_types: entity_type = UnionType("_Entity") self.types.append(entity_type) entity_type.type_resolver(self._entity_type_resolver) self.query.field("_entities")(self._entities_resolver) return make_executable_schema(self._get_federated_sdl(), self.types)
def test_union_type_resolver_may_be_set_using_setter(query_with_user_item): def resolve_result_type(*_): # pylint: disable=unused-variable return "User" union = UnionType("FeedItem") union.set_type_resolver(resolve_result_type) schema = make_executable_schema(type_defs, [query_with_user_item, union]) result = graphql_sync(schema, "{ item { __typename } }") assert result.data == {"item": {"__typename": "User"}}
def test_result_is_none_if_union_didnt_resolve_the_type( query_with_invalid_item): union = UnionType("FeedItem", type_resolver=resolve_result_type) schema = make_executable_schema(type_defs, [query_with_invalid_item, union]) result = graphql_sync(schema, test_query) assert result.data == {"item": None}
def test_result_is_thread_title_if_union_resolves_type_to_thread( query_with_thread_item, ): union = UnionType("FeedItem", type_resolver=resolve_result_type) schema = make_executable_schema(type_defs, [query_with_thread_item, union]) result = graphql_sync(schema, test_query) assert result.data == {"item": {"__typename": "Thread", "title": Thread.title}}
def create_schema_from_template(self): template = SERVICE_TEMPLATE entity_union_str = self._make_entity_str() entity_query_str = "" if entity_union_str != "": entity_union = UnionType("_Entity") entity_union.set_type_resolver(self.resolve_entities) self.query.set_field("_entities", self._entities) entity_query_str = ENTITY_QUERY self.federation_types.append(entity_union) template = template.format(union_entities=entity_union_str, entity_query=entity_query_str, query_str=self.sdl) return make_executable_schema( template, [self.query, _Any, _FieldSet] + [ObjectType(entity_name) for entity_name in self.entities.keys()] + self.federation_types, directives=self.directives)
def test_result_is_username_if_union_resolves_type_to_user( query_with_user_item): union = UnionType("FeedItem", type_resolver=resolve_result_type) schema = make_executable_schema(type_defs, [query_with_user_item, union]) result = graphql_sync(schema, test_query) assert result.data == { "item": { "__typename": "User", "username": User.username } }
def test_directive_can_be_defined_without_being_used(): type_defs = """ directive @customdirective on OBJECT | INTERFACE union UnionTest = Type1 | Type2 type Query { hello: String } type Type1 { foo: String } type Type2 { bar: String } """ class CustomDirective(SchemaDirectiveVisitor): def visit_object(self, object_): pass def visit_interface(self, interface): pass type_1 = ObjectType("Type1") type_2 = ObjectType("Type2") def resolve_union_test_type(*_): return "AccessError" # noop type resolver for test query = QueryType() union_test = UnionType("UnionTest", resolve_union_test_type) make_executable_schema( type_defs, [query, union_test, type_1, type_2], directives={"customdirective": CustomDirective}, )
def test_union_type_resolver_may_be_set_on_initialization(query_with_user_item): union = UnionType("FeedItem", type_resolver=lambda *_: "User") schema = make_executable_schema(type_defs, [query_with_user_item, union]) result = graphql_sync(schema, "{ item { __typename } }") assert result.data == {"item": {"__typename": "User"}}
def test_attempt_to_bind_union_to_invalid_type_raises_error(schema): union = UnionType("Query") with pytest.raises(ValueError): union.bind_to_schema(schema)
def test_attempt_to_bind_union_to_undefined_type_raises_error(schema): union = UnionType("Test") with pytest.raises(ValueError): union.bind_to_schema(schema)
"magazine": [m for m in magazines if m["branch"] == branch], "book": [b for b in books if b["branch"] == branch], } for i, branch in enumerate(libraries)] storage = [] mutation = MutationType() @mutation.field("storage_add") def mutate(self, info, string): storage.append(string) return {"string": string} item = UnionType("Item") @item.type_resolver def resolve_type(obj, *args): if "isbn" in obj: return "Book" elif "issue" in obj: # pylint: disable=R1705 return "Magazine" return None query = QueryType()
from ariadne import UnionType from classes.error import Error WALLET_RESPONSE = UnionType("BalanceResponse") @WALLET_RESPONSE.type_resolver def r_wallet_response(obj, *_): if isinstance(obj, Error): return "Error" return "NodeBalance"
from ariadne import UnionType from classes.error import Error CHANNEL_RESPONSE = UnionType("ChannelResponse") @CHANNEL_RESPONSE.type_resolver def r_channel_response(obj, *_): if isinstance(obj, Error): return "Error" return "ChannelPayload"
from ariadne import UnionType from classes.error import Error USER_INVOICE_RESPONSE = UnionType("UserInvoiceResponse") PAY_INVOICE_RESPONSE = UnionType("PaidInvoiceResponse") @USER_INVOICE_RESPONSE.type_resolver @PAY_INVOICE_RESPONSE.type_resolver def r_add_invoice_response(obj, _, resolve_type): if isinstance(obj, Error): return "Error" if str(resolve_type) == "PaidInvoiceResponse": return "PaidInvoice" if str(resolve_type) == "UserInvoiceResponse": return "UserInvoice"
from ariadne import UnionType from graph.graphql import Resolver def resolve_error_type(obj, *_): if obj.get("code"): return "AccessError" return "NotFoundError" error = UnionType("Error", resolve_error_type) Resolver(error)
from fastapi import FastAPI from fastapi.responses import ORJSONResponse from ariadne.asgi import GraphQL from ariadne import make_executable_schema, load_schema_from_path, format_error, UnionType from graphql import GraphQLError from graphql_objects import DatesCheck, GenericError, ListingUnsupportedError from resolvers import query dates_result = UnionType("DatesResult") @dates_result.type_resolver def resolve_ranked_search_type(obj, *_): if isinstance(obj, DatesCheck): return "DatesCheck" if isinstance(obj, GenericError): return "GenericError" if isinstance(obj, ListingUnsupportedError): return "ListingUnsupportedError" return None schema_definition = load_schema_from_path("schema.graphql") executable_schema = make_executable_schema(schema_definition, query, dates_result) def custom_error_formatter(error: GraphQLError, debug: bool) -> dict: if debug: return format_error(error, debug)
from typing import Union from ariadne import UnionType from pymacaroons import Macaroon from classes.user import User from classes.error import Error _MACAROON_RESPONSE = UnionType("MacaroonResponse") @_MACAROON_RESPONSE.type_resolver def r_token_response(obj: Union[User, Error], *_) -> str: if isinstance(obj, Error): return "Error" return "AuthPayload" _ATTENUATED_MACAROON_RESPONSE = UnionType("AttenuatedMacaroonResponse") @_ATTENUATED_MACAROON_RESPONSE.type_resolver def r_attenuated_response(obj, *_) -> str: if isinstance(obj, Error): return "Error" return "AttenuatedMacaroon" MACAROON_RESPONSES = [_MACAROON_RESPONSE, _ATTENUATED_MACAROON_RESPONSE]
from typing import Union from ariadne import UnionType from classes import Error from models import LSAT LSAT_REPONSE = UnionType("LSATResponse") @LSAT_REPONSE.type_resolver def r_lsat_response(obj: Union[LSAT, Error], *_) -> str: if isinstance(obj, Error): return "Error" return "LSATPayload"
from ariadne import UnionType from classes.error import Error from classes.user import User USER_RESPONSE = UnionType("UserResponse") @USER_RESPONSE.type_resolver def r_user_response(obj, *_): if isinstance(obj, Error): return "Error" if isinstance(obj, User): return "User" NEW_USER_RESPONSE = UnionType("NewUserResponse") @NEW_USER_RESPONSE.type_resolver def r_new_user_response(obj, *_): if isinstance(obj, Error): return "Error" if isinstance(obj, User): return "NewUser"
from ariadne import UnionType from models.invoice import Invoice from pymacaroons import Macaroon FEED_ITEM = UnionType("FeedItem") @FEED_ITEM.type_resolver def r_feed_item(obj, info, *_): m = Macaroon.deserialize( info.context["request"].headers["Authorization"].replace( "Bearer ", "")) if isinstance(obj, Invoice): if m.identifier == obj.payee: return "UserInvoice" if m.identifier == obj.payer: return "PaidInvoice" return "Deposit"
def get_schema(tmdb, database): # Setup queries query = QueryType() register_query_resolvers(query, tmdb) # Setup mutations mutation = MutationType() resolve_favorite, resolve_rating, resolve_number_of_watched_episodes, resolve_watch_status, resolve_country, resolve_language = register_mutation_resolvers( mutation, tmdb, database) # Register aliases for mutations favorite = MutationType() favorite.set_field("favorite", resolve_favorite) rating = MutationType() rating.set_field("rating", resolve_rating) number_of_watched_episodes = MutationType() # TODO: Alias number_of_watched_episodes.set_field("numberOfWatchedEpisodes", resolve_number_of_watched_episodes) watch_status = MutationType() # TODO: Alias watch_status.set_field("watchStatus", resolve_watch_status) country = MutationType() country.set_field("country", resolve_country) language = MutationType() language.set_field("language", resolve_language) # Register aliases for objects movie = ObjectType("Movie") movie.set_alias("ratingAverage", "rating_average") movie.set_alias("ratingCount", "rating_count") movie.set_alias("releaseInitial", "release_date") movie.set_alias("backdropPath", "backdrop_path") movie.set_alias("posterPath", "poster_path") movie.set_alias("tmdbUrl", "tmdb_url") movie.set_alias("watchStatus", "watch_status") movie.set_alias("ratingUser", "rating_user") tv = ObjectType("TV") tv.set_alias("ratingAverage", "rating_average") tv.set_alias("ratingCount", "rating_count") tv.set_alias("releaseInitial", "first_air_date") tv.set_alias("releaseFinal", "last_air_date") tv.set_alias("backdropPath", "backdrop_path") tv.set_alias("posterPath", "poster_path") tv.set_alias("numberOfEpisodes", "number_of_episodes") tv.set_alias("numberOfSeasons", "number_of_seasons") tv.set_alias("tmdbUrl", "tmdb_url") tv.set_alias("watchStatus", "watch_status") tv.set_alias("ratingUser", "rating_user") tv.set_alias("directors", "creators") season = ObjectType("Season") season.set_alias("tvCode", "tv_code") season.set_alias("seasonNumber", "season_number") season.set_alias("posterPath", "poster_path") season.set_alias("numberOfEpisodes", "number_of_episodes") season.set_alias("airDate", "air_date") season.set_alias("numberOfWatchedEpisodes", "number_of_watched_episodes") episode = ObjectType("Episode") episode.set_alias("episodeNumber", "episode_number") episode.set_alias("seasonNumber", "season_number") episode.set_alias("airDate", "air_date") episode.set_alias("ratingAverage", "rating_average") episode.set_alias("stillPath", "still_path") media_page = ObjectType("MediaPage") media_page.set_alias("totalPages", "total_pages") director = ObjectType("Director") director.set_alias("imagePath", "image_path") cast = ObjectType("Cast") cast.set_alias("imagePath", "image_path") searchResult = UnionType("Media") # Read the GraphQL schema type_defs = load_schema_from_path( os.path.join(os.path.dirname(__file__), "api.graphql")) # Connect the schema to the resolvers return make_executable_schema(type_defs, query, mutation, rating, watch_status, movie, tv, season, episode, media_page, director, cast, number_of_watched_episodes, favorite)
# Type definitions query = QueryType() mutation = MutationType() person = InterfaceType("Person") skill = ObjectType("Skill") # person = ObjectType("Person") eye_color = EnumType( "EyeColor", { 'BLUE': 'blue', 'GREEN': 'green', 'BROWN': 'brown', 'BLACK': 'black', }, ) global_search = UnionType("GlobalSearch") def create_persons(info, input): friends = [] skills = [] if 'friends' in input: person_ids = input.pop('friends') friends = session.query(Person).filter(Person.id.in_(person_ids)).all() if 'skills' in input: skill_ids = input.pop('skills') skills = session.query(Skill).filter(Skill.id.in_(skill_ids)).all() new_person = Person(**input) new_person.id = str(uuid4()) new_person.friends = friends
import copy from datetime import datetime from ariadne import UnionType, ScalarType, InterfaceType, ObjectType from web.data import ingredients, suppliers, products product_interface = InterfaceType('ProductInterface') product_type = UnionType('Product') ingredient_type = ObjectType('Ingredient') supplier_type = ObjectType('Supplier') datetime_scalar = ScalarType('Datetime') @datetime_scalar.serializer def serialize_datetime_scalar(date): return date.isoformat() @datetime_scalar.value_parser def parse_datetime_scalar(date): return datetime.fromisoformat(date) @product_type.type_resolver def resolve_product_type(obj, *_): if 'hasFilling' in obj: return 'Cake' return 'Beverage'
accessmod_mutations = MutationType() # Projects project_object = ObjectType("AccessmodProject") project_order_by = EnumType( "AccessmodProjectOrder", { "UPDATED_AT_DESC": "-updated_at", "UPDATED_AT_ASC": "updated_at", "NAME_DESC": "-name", "NAME_ASC": "name", }, ) owner_union = UnionType("AccessmodOwner") @owner_union.type_resolver def resolve_accessmod_owner_type(obj, *_): if isinstance(obj, Team): return "Team" elif isinstance(obj, User): return "User" ownership_interface = InterfaceType("AccessmodOwnership") @ownership_interface.type_resolver def resolve_ownership_type(obj, *_):