def from_list_argument(self, list_: StrawberryArgument) -> GraphQLList: assert list_.child is not None of_type = self.get_graphql_type_argument(list_.child) return GraphQLList(of_type)
def get_field_type(self, map, type): if isinstance(type, List): return GraphQLList(self.get_field_type(map, type.of_type)) if isinstance(type, NonNull): return GraphQLNonNull(self.get_field_type(map, type.of_type)) return map.get(type._meta.name)
from easydict import EasyDict as edict from graphql import (GraphQLField, GraphQLNonNull, GraphQLString, GraphQLArgument, GraphQLList) from ..types import (AuthenticationType, UserType) from ...utils.resolver import resolver_wrapper from ...resolvers.user import (register_user, authenticate_user, update_roles) from ...middlewares import authorize RegisterUserMutation = GraphQLField( AuthenticationType, args={ 'primaryEmail': GraphQLArgument(GraphQLNonNull(GraphQLString)), 'password': GraphQLArgument(GraphQLNonNull(GraphQLString)), 'secondaryEmails': GraphQLArgument(GraphQLList(GraphQLString)), 'givenNames': GraphQLArgument(GraphQLList(GraphQLString)), 'familyName': GraphQLArgument(GraphQLString), 'nickname': GraphQLArgument(GraphQLString) }, resolver=lambda _, info, **kwargs: resolver_wrapper( register_user, edict(info.context), kwargs['primaryEmail'], kwargs[ 'password'], kwargs.get('secondaryEmails', None), kwargs.get('givenNames', None), kwargs.get('familyName', None), kwargs.get('nickname', None))) AuthenticateMutation = GraphQLField( AuthenticationType, args={ 'primaryEmail': GraphQLArgument(GraphQLNonNull(GraphQLString)), 'password': GraphQLArgument(GraphQLNonNull(GraphQLString))
('subject', GraphQLField(GraphQLString)), ('message', GraphQLField(GraphQLString)), ('unread', GraphQLField(GraphQLBoolean)), ])) InboxType = GraphQLObjectType( name='Inbox', fields=OrderedDict([ ('total', GraphQLField(GraphQLInt, resolver=lambda inbox, context: len(inbox.emails))), ('unread', GraphQLField(GraphQLInt, resolver=lambda inbox, context: len( [e for e in inbox.emails if e.unread]))), ('emails', GraphQLField(GraphQLList(EmailType))), ])) QueryType = GraphQLObjectType(name='Query', fields=OrderedDict([ ('inbox', GraphQLField(InboxType)), ])) EmailEventType = GraphQLObjectType( name='EmailEvent', fields=OrderedDict([ ('email', GraphQLField(EmailType, resolver=lambda root, info: root[0])), ('inbox', GraphQLField(InboxType, resolver=lambda root, info: root[1])), ]))
def __init__(self): super().__init__(self) loop = tornado.ioloop.IOLoop.current() self.service_command_name = "MaverickService" self.process_runner_timeout = 5 # seconds self.using_dbus = options.use_dbus # self.service_command_category_name = self.service_command_name + "Category" self.service_command_list_name = self.service_command_name + "List" self.service_definition_path = ( pathlib.Path(options.service_definition_path).expanduser().resolve() ) self.meta_info_file = "__init__" if self.using_dbus: self.services = self.read_services_dbus() else: self.services = self.read_services() if self.using_dbus: self.stop_event = asyncio.Event() loop.add_callback(self.monitor) self.service_command_type = GraphQLObjectType( self.service_command_name, lambda: { "name": GraphQLField( GraphQLString, description="Service identifier name", ), "displayName": GraphQLField( GraphQLString, description="Service display name", ), "category": GraphQLField( GraphQLString, description="Service category identifier", ), "displayCategory": GraphQLField( GraphQLString, description="Service category name", ), "enabled": GraphQLField( GraphQLBoolean, description="If the service is enabled at boot", ), "running": GraphQLField( GraphQLBoolean, description="If the service is currently running" ), "updateTime": GraphQLField( GraphQLInt, description="Time when the service status was last updated", ), }, description="Maverick service interface", ) self.service_command_list_type = GraphQLObjectType( self.service_command_list_name, lambda: {"services": GraphQLField(GraphQLList(self.service_command_type)),}, ) self.q = { self.service_command_name: GraphQLField( self.service_command_type, args={ "name": GraphQLArgument( GraphQLString, description="Service identifier name", ), "category": GraphQLArgument( GraphQLString, description="Service category identifier", ), }, resolve=self.get_service_status, ), self.service_command_list_name: GraphQLField( self.service_command_list_type, resolve=self.get_service_status_list, ), } self.m = { self.service_command_name: GraphQLField( self.service_command_type, args=self.get_mutation_args(self.service_command_type), resolve=self.set_service_status, ) } self.s = { self.service_command_name: GraphQLField( self.service_command_type, subscribe=self.sub_service_status, resolve=None, ) }
def test_ast_from_value_with_list_type_and_non_iterable_value(): assert ast_from_value(5, GraphQLList(GraphQLInt)) == IntValueNode(value="5")
""" """ # get the nameserver ns = pyre.executive.nameserver # get all relevant (name, slot) pairs yield from ns.find(pattern=pattern) # all done return # query query = GraphQLObjectType(name="Query", fields={ 'traits': GraphQLField( GraphQLList(traitObjectType), args={ "pattern": GraphQLArgument(GraphQLString), }, resolve=lookupTraits, ) }) # schema schema = GraphQLSchema(query=query) # declaration class GraphQL: def resolve(self, server, request, query, operation, variables):
def list_of(ttype: GraphQLType) -> GraphQLList: return GraphQLList(type=ttype)
def test_argument_types(self) -> None: valid_values_type = Tuple[Any, ...] invalid_values_type = Tuple[Any, ...] test_case_type = Tuple[GraphQLSchemaFieldType, valid_values_type, invalid_values_type] test_cases: Tuple[test_case_type, ...] = ( (GraphQLString, ("asdf", ), (4, 5.4, True)), (GraphQLID, ("13d72846-1777-6c3a-5743-5d9ced3032ed", "asf"), (4, 4.4, True)), (GraphQLFloat, (4.1, 4.0), ("4.3", 5)), (GraphQLInt, (3, 4), (4.0, 4.1, True, False, "4")), (GraphQLBoolean, ( True, False, ), ("True", 0, 1, 0.4)), (GraphQLDecimal, (Decimal(4), 0.4, 4), (True, "sdfsdf")), ( GraphQLDate, ( datetime.date(2007, 12, 6), datetime.date(2008, 12, 6), datetime.date(2009, 12, 6), ), ( "2007-12-06", datetime.datetime(2007, 12, 6, 16, 29, 43, 79043), ), ), ( GraphQLDateTime, ( datetime.datetime(2007, 12, 6, 16, 29, 43, 79043), datetime.datetime(2007, 12, 6), ), ( "2007-12-06T16:29:43", datetime.date(2007, 12, 6), datetime.datetime(2008, 12, 6, 16, 29, 43, 79043, tzinfo=pytz.utc), datetime.datetime(2009, 12, 6, 16, 29, 43, 79043, tzinfo=pytz.timezone("US/Eastern")), ), ), (GraphQLList(GraphQLInt), ([], [1], [3, 5]), (4, ["a"], [1, "a"], [True])), (GraphQLList(GraphQLString), ([], ["a"]), (1, "a", ["a", 4])), ) arbitrary_argument_name = "arbitrary_name" for graphql_type, valid_values, invalid_values in test_cases: for valid_value in valid_values: validate_argument_type(arbitrary_argument_name, graphql_type, valid_value) for invalid_value in invalid_values: with self.assertRaises(GraphQLInvalidArgumentError): validate_argument_type(arbitrary_argument_name, graphql_type, invalid_value)
def get_fields(self, typename): fields = OrderedDict() if typename == 'Query': for name, gqltype in sorted(self._gql_interfaces.items(), key=lambda x: x[1].name): if name in TOP_LEVEL_TYPES: continue fields[gqltype.name] = GraphQLField( GraphQLList(GraphQLNonNull(gqltype)), args=self._get_query_args(name), ) elif typename == 'Mutation': for name, gqltype in sorted(self._gql_objtypes.items(), key=lambda x: x[1].name): if name in TOP_LEVEL_TYPES: continue gname = self.get_gql_name(name) fields[f'delete_{gname}'] = GraphQLField( GraphQLList(GraphQLNonNull(gqltype)), args=self._get_query_args(name), ) args = self._get_insert_args(name) if args: fields[f'insert_{gname}'] = GraphQLField( GraphQLList(GraphQLNonNull(gqltype)), args=args, ) for name, gqltype in sorted(self._gql_interfaces.items(), key=lambda x: x[1].name): if (name in TOP_LEVEL_TYPES or f'Update{name}' not in self._gql_inobjtypes): continue gname = self.get_gql_name(name) args = self._get_update_args(name) if args: fields[f'update_{gname}'] = GraphQLField( GraphQLList(GraphQLNonNull(gqltype)), args=args, ) else: edb_type = self.edb_schema.get(typename) pointers = edb_type.get_pointers(self.edb_schema) for name, ptr in sorted(pointers.items(self.edb_schema)): if name == '__type__': continue # We want to look at the pointer lineage because that # will be reflected into GraphQL interface that is # being extended and the type cannot be changed. lineage = s_objects.compute_lineage(self.edb_schema, ptr) # We want the first non-generic ancestor of this # pointer as its target type will dictate the target # types of all its derived pointers. # # NOTE: We're guaranteed to have a non-generic one # since we're inspecting the lineage of a pointer # belonging to an actual type. for ancestor in reversed(lineage): if not ancestor.generic(self.edb_schema): ptr = ancestor break target = self._get_target(ptr) if target is not None: if ptr.get_target(self.edb_schema).is_object_type(): args = self._get_query_args( ptr.get_target(self.edb_schema).get_name( self.edb_schema)) else: args = None fields[name] = GraphQLField(target, args=args) return fields
'dnsQuery': GraphQLInputObjectField(type=GraphQLString, description='Threat dns query name'), 'clientIp': GraphQLInputObjectField(type=SpotIpType, description='Threat client IP'), 'title': GraphQLInputObjectField(type=GraphQLNonNull(GraphQLString), description='Threat title'), 'text': GraphQLInputObjectField(type=GraphQLNonNull(GraphQLString), description='Threat title description'), 'threatDetails': GraphQLInputObjectField( type=GraphQLNonNull( GraphQLList(GraphQLNonNull(ThreatDetailsInputType))), description='Threat details. See DnsThreatInformation.details') }) def _score_records(args): results = [] _input = args.get('input') for cmd in _input: _date = cmd.get('date', date.today()) dns_query = cmd.get('dnsQuery', '') client_ip = cmd.get('clientIp', '') query_score = cmd.get('score') if dns_query else 0 client_ip_score = cmd.get('score') if client_ip else 0
description='Threat title', resolver=lambda root, *_: root.get('title') ), 'text': GraphQLField( type=GraphQLString, description='Threat description', resolver=lambda root, *_: root.get('text') ) } ) ThreatsInformationType = GraphQLObjectType( name='ProxyThreatsType', fields={ 'list': GraphQLField( type=GraphQLList(ScoredRequestType), description='List of URIs that have been scored', args={ 'date': GraphQLArgument( type=SpotDateType, description='A date to use as reference to retrieve the list of scored URI. Defaults to today' ) }, resolver=lambda root, args, *_: Proxy.get_scored_requests(date=args.get('date', date.today())) ), 'comments': GraphQLField( type=GraphQLList(CommentType), description='A list of comments about threats', args={ 'date': GraphQLArgument( type=SpotDateType,
GraphQLArgument, GraphQLNonNull, GraphQLString, GraphQLList, print_schema, GraphQLSchema, GraphQLObjectType, GraphQLField, GraphQLInt, GraphQLFloat, GraphQLBoolean, ) GRAPHQL_TYPE_MAPPING = { VSSDataType.INT8: GraphQLInt, VSSDataType.INT8_ARRAY: GraphQLList(GraphQLInt), VSSDataType.UINT8: GraphQLInt, VSSDataType.UINT8_ARRAY: GraphQLList(GraphQLInt), VSSDataType.INT16: GraphQLInt, VSSDataType.INT16_ARRAY: GraphQLList(GraphQLInt), VSSDataType.UINT16: GraphQLInt, VSSDataType.UINT16_ARRAY: GraphQLList(GraphQLInt), VSSDataType.INT32: GraphQLInt, VSSDataType.INT32_ARRAY: GraphQLList(GraphQLInt), VSSDataType.UINT32: GraphQLFloat, VSSDataType.UINT32_ARRAY: GraphQLList(GraphQLFloat), VSSDataType.INT64: GraphQLFloat, VSSDataType.INT64_ARRAY: GraphQLList(GraphQLFloat), VSSDataType.UINT64: GraphQLFloat, VSSDataType.UINT64_ARRAY: GraphQLList(GraphQLFloat), VSSDataType.FLOAT: GraphQLFloat,
def from_list_field(self, list_: StrawberryField) -> GraphQLList: assert list_.child is not None of_type = self.get_graphql_type_field(list_.child) return GraphQLList(of_type)
REPRESENTATIVE_DATA_FOR_EACH_TYPE = { # Not including GraphQLID since it can be a string or an int, # and is implicitly coerced to a string by the GraphQL library. GraphQLBoolean: True, GraphQLFloat: 3.14159, GraphQLInt: 42, GraphQLString: "foobar", GraphQLDate: date(2017, 3, 22), GraphQLDateTime: datetime(2017, 3, 22, 9, 54, 35, tzinfo=pytz.utc), GraphQLList(GraphQLString): ["foo", "bar", "baz"], GraphQLList(GraphQLInt): [1, 2, 3, 4, 5], GraphQLList(GraphQLDate): [date(2017, 1, 22), date(2017, 1, 23), date(2017, 1, 24)], GraphQLList(GraphQLDateTime): [ datetime(2017, 1, 22, 9, 54, 35, tzinfo=pytz.utc), arrow.get(2017, 1, 23, 9, 54, 35, tzinfo=pytz.utc), arrow.get(datetime(2017, 1, 24, 9, 54, 35, tzinfo=pytz.utc)), ], } class SafeMatchFormattingTests(unittest.TestCase): def test_safe_match_argument_for_strings(self):
('published', GraphQLEnumValue('published')), ('archived', GraphQLEnumValue('archived')), ]) ) ContestType = GraphQLObjectType( name='ContestType', fields=lambda: { 'id': GraphQLField(GraphQLID), 'code': GraphQLField(GraphQLNonNull(GraphQLString)), 'title': GraphQLField(GraphQLNonNull(GraphQLString)), 'description': GraphQLField(GraphQLString), 'status': GraphQLField(GraphQLNonNull(ContestStatusType)), 'createdAt': GraphQLField(GraphQLNonNull(GraphQLString)), 'names': GraphQLField( GraphQLList(NameType), resolver=lambda contest, info, **kwargs: resolve_with_loader( 'names_by_contest_id', info.context, contest.id, [] ), ), 'createdBy': GraphQLField( GraphQLNonNull(UserType), resolver=lambda name, info, **kwargs: resolve_with_loader( 'user_by_id', info.context, name.createdBy )
def test_nested_lists_are_disallowed(self): value = [[1, 2, 3], [4, 5, 6]] graphql_type = GraphQLList(GraphQLList(GraphQLInt)) with self.assertRaises(GraphQLInvalidArgumentError): _safe_match_argument(graphql_type, value)
'NEWHOPE': GraphQLEnumValue(4, description='Released in 1977.'), 'EMPIRE': GraphQLEnumValue(5, description='Released in 1980.'), 'JEDI': GraphQLEnumValue(6, description='Released in 1983.') }, description='One of the films in the Star Wars Trilogy') character_interface = GraphQLInterfaceType( 'Character', lambda: { 'id': GraphQLField(GraphQLNonNull(GraphQLString), description='The id of the character.'), 'name': GraphQLField(GraphQLString, description='The name of the character.'), 'friends': GraphQLField(GraphQLList(character_interface), description='The friends of the character,' ' or an empty list if they have none.'), 'appearsIn': GraphQLField(GraphQLList(episode_enum), description='Which movies they appear in.'), 'secretBackstory': GraphQLField(GraphQLString, description='All secrets about their past.') }, resolve_type=lambda character, _info: { 'Human': human_type, 'Droid': droid_type }.get(character.type), description='A character in the Star Wars Trilogy')
TaskSolution, resolve=get_task_my_solution), }) Session = GraphQLObjectType( name='Session', interfaces=[NodeInterface], fields={ 'id': GraphQLField( GraphQLNonNull(GraphQLID), resolve=lambda s, _: f'Session:{s.course_id}:{s.slug}'), 'slug': GraphQLField( GraphQLString), 'date': GraphQLField( GraphQLString), 'titleHTML': GraphQLField( GraphQLString, resolve=lambda s, _: s.title_html), 'hasTasks': GraphQLField( GraphQLBoolean, resolve=lambda s, _: bool(s.task_items)), 'materialItems': GraphQLField( GraphQLList(MaterialItem), resolve=lambda s, _: s.material_items), 'taskItems': GraphQLField( GraphQLList(TaskItem), resolve=lambda s, _: s.task_items), })
def list_of(ttype): return GraphQLList(type=ttype)
async def test_plop(): EmailType = GraphQLObjectType( "Email", { "from": GraphQLField(GraphQLString), "subject": GraphQLField(GraphQLString), "message": GraphQLField(GraphQLString), "unread": GraphQLField(GraphQLBoolean), }, ) InboxType = GraphQLObjectType( "Inbox", { "total": GraphQLField(GraphQLInt, resolve=lambda inbox, _info: len(inbox["emails"])), "unread": GraphQLField( GraphQLInt, resolve=lambda inbox, _info: sum(1 for email in inbox["emails"] if email["unread"]), ), "emails": GraphQLField(GraphQLList(EmailType)), }, ) EmailEventType = GraphQLObjectType( "EmailEvent", { "email": GraphQLField(EmailType), "inbox": GraphQLField(InboxType) }, ) QueryType = GraphQLObjectType("Query", {"inbox": GraphQLField(InboxType)}) def email_schema_with_resolvers(subscribe_fn=None, resolve_fn=None): return GraphQLSchema( QueryType, subscription=GraphQLObjectType( "Subscription", { "importantEmail": GraphQLField( EmailEventType, args={"priority": GraphQLArgument(GraphQLInt)}, resolve=resolve_fn, subscribe=subscribe_fn, ) }, ), ) async def subscribe_fn(_data, _info): yield {"email": {"subject": "Hello"}} yield {"email": {"subject": "Goodbye"}} yield {"email": {"subject": "Bonjour"}} def resolve_fn(event, _info): if event["email"]["subject"] == "Goodbye": raise RuntimeError("Never leave") return event erroring_email_schema = email_schema_with_resolvers( subscribe_fn, resolve_fn) print(print_schema(erroring_email_schema)) subscription = await subscribe( erroring_email_schema, parse(""" subscription { importantEmail { email { subject } } } """), ) payload1 = await anext(subscription) assert payload1 == ({ "importantEmail": { "email": { "subject": "Hello" } } }, None) # An error in execution is presented as such. payload2 = await anext(subscription) assert payload2 == ( { "importantEmail": None }, [{ "message": "Never leave", "locations": [(3, 15)], "path": ["importantEmail"], }], ) # However that does not close the response event stream. Subsequent events are # still executed. payload3 = await anext(subscription) assert payload3 == ({ "importantEmail": { "email": { "subject": "Bonjour" } } }, None)
def __init__(self): super().__init__() self.vehicle_info_data = {} self.vehicle_info_meta = {"meta": {"total": 0, "updateTime": int(time.time())}} self.vehicle_info_type = GraphQLObjectType( "VehicleInfo", lambda: { "uuid": GraphQLField( GraphQLString, description="The UUID of the vehicle." ), "sysid": GraphQLField(GraphQLInt, description="System ID"), "compid": GraphQLField(GraphQLInt, description="Component ID"), "autopilot": GraphQLField( GraphQLInt, description="Autopilot ID (maps to value defined in mavlink)", ), "autopilotString": GraphQLField( GraphQLString, description="Autopilot string from mavlink mapping" ), "type": GraphQLField( GraphQLInt, description="Type ID (maps to value defined in mavlink)" ), "typeString": GraphQLField( GraphQLString, description="Type string from mavlink mapping" ), "capabilities": GraphQLField(GraphQLInt, description="Bit field"), "flightSoftwareVersion": GraphQLField(GraphQLInt, description=""), "middlewareSoftwareVersion": GraphQLField(GraphQLInt, description=""), "osSoftwareVersion": GraphQLField(GraphQLInt, description=""), "boardVersion": GraphQLField(GraphQLInt, description=""), "vendorId": GraphQLField(GraphQLInt, description=""), "productId": GraphQLField(GraphQLInt, description=""), "uid": GraphQLField(GraphQLInt, description=""), "updateTime": GraphQLField(GraphQLInt, description=""), }, description="Vehicle info", ) self.vehicle_info_list_type = GraphQLObjectType( "VehicleInfoList", lambda: { "info": GraphQLField(GraphQLList(self.vehicle_info_type)), "total": GraphQLField( GraphQLInt, description="Total number of info entries" ), "updateTime": GraphQLField(GraphQLInt, description=""), }, ) self.q = { "VehicleInfo": GraphQLField( self.vehicle_info_type, args={ "uuid": GraphQLArgument( GraphQLNonNull(GraphQLString), description="The UUID of the vehicle", ) }, resolve=self.get_vehicle_info, ), "VehicleInfoList": GraphQLField( self.vehicle_info_list_type, resolve=self.get_vehicle_info_list ), } self.m = { "VehicleInfo": GraphQLField( self.vehicle_info_type, args=self.get_mutation_args(self.vehicle_info_type), resolve=self.update_vehicle_info, ) } self.s = { "VehicleInfo": GraphQLField( self.vehicle_info_type, subscribe=self.sub_vehicle_info, resolve=None ), "VehicleInfoList": GraphQLField( self.vehicle_info_list_type, subscribe=self.sub_vehicle_info_list, resolve=None, ), }
type=GraphQLString, description='DNS query class name', resolver=lambda root, *_: root.get('dns_qry_class_name') ), 'dnsQueryTypeLabel': GraphQLField( type=GraphQLString, description='DNS query type name', resolver=lambda root, *_: root.get('dns_qry_type_name') ), 'dnsQueryRcodeLabel': GraphQLField( type=GraphQLString, description='DNS query response code name', resolver=lambda root, *_: root.get('dns_qry_rcode_name') ), 'dnsQueryAnswers': GraphQLField( type=GraphQLList(GraphQLString), description='DNS answers', resolver=lambda root, *_: root.get('dns_a', '').split('|') ), 'unixTimestamp': GraphQLField( type=GraphQLInt, description='Frame unix timestamp', resolver=lambda root, *_: root.get('unix_tstamp') or 0 ) } ) ThreatDetailsType = GraphQLObjectType( name='DnsThreatDetailsType', fields={ 'total': GraphQLField(
from graphql import (GraphQLField, GraphQLNonNull, GraphQLString, GraphQLInt, GraphQLList, GraphQLArgument) from ..types import ChatMessageType from ...resolvers.queries import replay_messages ReplayMessagesQuery = GraphQLField( GraphQLList(ChatMessageType), { 'startDate': GraphQLArgument(GraphQLNonNull(GraphQLString)), 'endDate': GraphQLArgument(GraphQLNonNull(GraphQLString)), 'maxMessages': GraphQLArgument(GraphQLInt, default_value=5) }, replay_messages)
# - 'op_name' can only contain characters [A-Za-z_]; # - cannot be used at or within vertex fields marked @fold; # - strings in 'value' can be encoded as '%tag_name' if referring to a tag named 'tag_name', # or as '$parameter_name' if referring to a parameter 'parameter_name' which will be provided # to the query at execution time. FilterDirective = GraphQLDirective( name='filter', args=OrderedDict([ ('op_name', GraphQLArgument( type=GraphQLNonNull(GraphQLString), description='Name of the filter operation to perform.', )), ('value', GraphQLArgument( type=GraphQLNonNull(GraphQLList(GraphQLNonNull(GraphQLString))), description='List of string operands for the operator.', )) ]), locations=[ DirectiveLocation.FIELD, DirectiveLocation.INLINE_FRAGMENT, ]) # Constraints: # - 'tag_name' can only contain characters [A-Za-z_]; # - 'tag_name' has to be distinct for each @output directive; # - can only be applied to property fields; # - cannot be applied to fields within a scope marked @fold. TagDirective = GraphQLDirective( name='tag',
from ..query.service import resolve_status from graphql import GraphQLObjectType, GraphQLField, \ GraphQLString, GraphQLInt, GraphQLList PortsType = GraphQLObjectType(name="Ports", fields={ "internal": GraphQLField(GraphQLString, resolve=lambda x, i: x[1]), "external": GraphQLField(GraphQLString, resolve=lambda x, i: x[0]) }) ServiceType = GraphQLObjectType(name="Service", fields={ "name": GraphQLField(GraphQLString), "image": GraphQLField(GraphQLString), "status": GraphQLField(GraphQLInt, resolve=resolve_status), "ports": GraphQLField(GraphQLList(PortsType)), })
def _process_has_edge_degree_filter_directive(filter_operation_info, location, context, parameters): """Return a Filter basic block that checks the degree of the edge to the given vertex field. Args: filter_operation_info: FilterOperationInfo object, containing the directive and field info of the field where the filter is to be applied. location: Location where this filter is used. context: dict, various per-compilation data (e.g. declared tags, whether the current block is optional, etc.). May be mutated in-place in this function! parameters: list of 1 element, containing the value to check the edge degree against; if the parameter is optional and missing, the check will return True. Returns: a Filter basic block that performs the check """ if isinstance(filter_operation_info.field_ast, InlineFragmentNode): raise AssertionError( u'Received InlineFragment AST node in "has_edge_degree" filter ' u"handler. This should have been caught earlier: " u"{}".format(filter_operation_info.field_ast)) filtered_field_name = filter_operation_info.field_name if filtered_field_name is None or not is_vertex_field_name( filtered_field_name): raise AssertionError( u'Invalid value for "filtered_field_name" in "has_edge_degree" ' u"filter: {}".format(filtered_field_name)) filtered_field_type = filter_operation_info.field_type if not is_vertex_field_type(filtered_field_type): raise AssertionError( u'Invalid value for "filter_operation_info.field_type" in ' u'"has_edge_degree" filter: {}'.format(filter_operation_info)) argument = parameters[0] if not is_runtime_parameter(argument): raise GraphQLCompilationError( u'The "has_edge_degree" filter only supports runtime ' u"variable arguments. Tagged values are not supported." u"Argument name: {}".format(argument)) argument_inferred_type = GraphQLInt argument_expression, non_existence_expression = _represent_argument( location, context, argument, argument_inferred_type) if non_existence_expression is not None: raise AssertionError( u"Since we do not support tagged values, non_existence_expression " u"should have been None. However, it was: " u"{}".format(non_existence_expression)) # HACK(predrag): Make the handling of vertex field types consistent. Currently, sometimes we # accept lists, and sometimes we don't. Both `Animal` and `[Animal]` should be # acceptable, since the difference there communicates a cardinality constraint # on the edge in question. # Issue: https://github.com/kensho-technologies/graphql-compiler/issues/329 hacked_field_type = GraphQLList(filtered_field_type) # If no edges to the vertex field exist, the edges' field in the database may be "null". # We also don't know ahead of time whether the supplied argument is zero or not. # We have to accommodate these facts in our generated comparison code. # We construct the following expression to check if the edge degree is zero: # ({argument} == 0) && (edge_field == null) argument_is_zero = expressions.BinaryComposition(u"=", argument_expression, expressions.ZeroLiteral) edge_field_is_null = expressions.BinaryComposition( u"=", expressions.LocalField(filtered_field_name, hacked_field_type), expressions.NullLiteral, ) edge_degree_is_zero = expressions.BinaryComposition( u"&&", argument_is_zero, edge_field_is_null) # The following expression will check for a non-zero edge degree equal to the argument. # (edge_field != null) && (edge_field.size() == {argument}) edge_field_is_not_null = expressions.BinaryComposition( u"!=", expressions.LocalField(filtered_field_name, hacked_field_type), expressions.NullLiteral, ) edge_degree = expressions.UnaryTransformation( u"size", expressions.LocalField(filtered_field_name, hacked_field_type)) edge_degree_matches_argument = expressions.BinaryComposition( u"=", edge_degree, argument_expression) edge_degree_is_non_zero = expressions.BinaryComposition( u"&&", edge_field_is_not_null, edge_degree_matches_argument) # We combine the two cases with a logical-or to handle both situations: filter_predicate = expressions.BinaryComposition(u"||", edge_degree_is_zero, edge_degree_is_non_zero) return blocks.Filter(filter_predicate)
( "total", GraphQLField( GraphQLInt, resolver=lambda inbox, context: len(inbox.emails) ), ), ( "unread", GraphQLField( GraphQLInt, resolver=lambda inbox, context: len( [e for e in inbox.emails if e.unread] ), ), ), ("emails", GraphQLField(GraphQLList(EmailType))), ] ), ) QueryType = GraphQLObjectType( name="Query", fields=OrderedDict([("inbox", GraphQLField(InboxType))]) ) EmailEventType = GraphQLObjectType( name="EmailEvent", fields=OrderedDict( [ ("email", GraphQLField(EmailType, resolver=lambda root, info: root[0])), ("inbox", GraphQLField(InboxType, resolver=lambda root, info: root[1])), ]
def test_deserialize_lists(self) -> None: # Non-collection with self.assertRaises(GraphQLInvalidArgumentError): deserialize_argument("numbers", GraphQLList(GraphQLInt), 1) # Tuple with self.assertRaises(GraphQLInvalidArgumentError): deserialize_argument("numbers", GraphQLList(GraphQLInt), (1, 2)) # Second element is of unexpected kind. with self.assertRaises(GraphQLInvalidArgumentError): deserialize_argument("numbers", GraphQLList(GraphQLInt), (1, 1.2, 3)) # Second element is "unparseable". with self.assertRaises(GraphQLInvalidArgumentError): deserialize_argument("numbers", GraphQLList(GraphQLInt), (1, "asda", 3)) # Basic self.assertEqual( [1.2, 2.3], deserialize_argument("numbers", GraphQLList(GraphQLFloat), [1.2, 2.3]) ) # With empty list self.assertEqual([], deserialize_argument("numbers", GraphQLList(GraphQLFloat), [])) # With list with one element self.assertEqual([1.2], deserialize_argument("numbers", GraphQLList(GraphQLFloat), [1.2])) # With outer null wrapper. self.assertEqual( [1.2, 2.3], deserialize_argument("numbers", GraphQLNonNull(GraphQLList(GraphQLFloat)), [1.2, 2.3]), ) # With inner null wrapper. self.assertEqual( [1.2, 2.3], deserialize_argument("numbers", GraphQLList(GraphQLNonNull(GraphQLFloat)), [1.2, 2.3]), ) # With outer and inner null wrapper. self.assertEqual( [1.2, 2.3], deserialize_argument( "numbers", GraphQLNonNull(GraphQLList(GraphQLNonNull(GraphQLFloat))), [1.2, 2.3] ), ) # With custom scalar type self.assertEqual( [datetime.date(2014, 2, 5)], deserialize_argument("dates", GraphQLList(GraphQLDate), ["2014-02-05"]), )
def __graphql__(self): return GraphQLList(_to_graphql_core_type(self.of_type))