def generate_graphql_type(graph_type): if graph_type == schema.Boolean: return graphql.GraphQLNonNull(graphql.GraphQLBoolean) elif graph_type == schema.Float: return graphql.GraphQLNonNull(graphql.GraphQLFloat) elif graph_type == schema.Int: return graphql.GraphQLNonNull(graphql.GraphQLInt) elif graph_type == schema.String: return graphql.GraphQLNonNull(graphql.GraphQLString) elif isinstance(graph_type, schema.EnumType): # TODO: should enums map names or values? values = iterables.to_dict( (member.value, graphql.GraphQLEnumValue(member.value)) for member in graph_type.enum) graphql_type = graphql.GraphQLEnumType(graph_type.name, values=values) return graphql.GraphQLNonNull(graphql_type) elif isinstance(graph_type, schema.InputObjectType): return graphql.GraphQLNonNull( graphql.GraphQLInputObjectType( name=graph_type.name, fields=lambda: iterables.to_dict( (snake_case_to_camel_case(field.name), to_graphql_input_field(field)) for field in graph_type.fields), )) elif isinstance(graph_type, schema.InterfaceType): return graphql.GraphQLNonNull( graphql.GraphQLInterfaceType( name=graph_type.name, fields=to_graphql_fields(graph_type.fields), resolve_type=lambda: None, )) elif isinstance(graph_type, schema.ListType): return graphql.GraphQLNonNull( graphql.GraphQLList(to_graphql_type(graph_type.element_type))) elif isinstance(graph_type, schema.NullableType): return to_graphql_type(graph_type.element_type).of_type elif isinstance(graph_type, schema.ObjectType): return graphql.GraphQLNonNull( graphql.GraphQLObjectType( name=graph_type.name, fields=to_graphql_fields(graph_type.fields), interfaces=tuple( to_graphql_type(interface).of_type for interface in graph_type.interfaces), )) else: raise ValueError("unsupported type: {}".format(graph_type))
def exec_thunk(thunk: TypeThunk, *, non_null=None) -> Any: result = thunk if isinstance(thunk, graphql.GraphQLType) else thunk() if non_null is True and not isinstance(result, graphql.GraphQLNonNull): return graphql.GraphQLNonNull(result) # type: ignore if non_null is False and isinstance(result, graphql.GraphQLNonNull): return result.of_type return result
def name_cache(name: Optional[str], description: Optional[str]) -> graphql.GraphQLNonNull: if name is None: return graphql.GraphQLNonNull( factory.factory(name, description)) # type: ignore # Method is in cache key because scalar types will have the same method, # and then be shared by both visitors, while input/output types will have # their own cache entry. if (name, method, description) in self._cache_by_name: tp, cached_args = self._cache_by_name[(name, method, description)] if cached_args == (args, kwargs): return tp tp = graphql.GraphQLNonNull(factory.factory( name, description)) # type: ignore # Don't put args in cache in order to avoid hashable issue self._cache_by_name[(name, method, description)] = (tp, (args, kwargs)) return tp
def _handle_nullability(self, gql_t, allow_null): gql_t = graphql.get_nullable_type(gql_t) if ( allow_null is False or allow_null is MISSING and self.ctx.explicit_nullability ): gql_t = graphql.GraphQLNonNull(gql_t) return gql_t
def test_overriding_int(): def new_int_mapper(mapper, ty): if ty is int: return NOT_AN_INT local_mapper = MAPPER.new() local_mapper.add_mapper(new_int_mapper) assert is_equal_type( MAPPER.map(int), graphql.GraphQLNonNull(graphql.GraphQLInt) )
def build_index_type(config, engine, index, n=5000): """ Examine records from the index to build GraphQL objects and input types for querying the index. """ logging.info('Building object type for %s...', index.name) # grab a single object from the index to build the schema object from reader = fetch_all(config, index.s3_prefix, key_limit=5) # read up to N records to get a good approx of all available fields records = [r for _, r in zip(range(n), reader.records)] # graphql object type (and subtypes) for the index obj_type = build_object_type(index.table.name, records) # add all the arguments used to query the index args = {} for col in index.schema.key_columns: field, *rest = col.split('|') # only use the first column name, assumes synonym fields args[field] = graphql.GraphQLNonNull(graphql.GraphQLID) # does this index's schema have a locus argument? if index.schema.has_locus: if index.schema.locus_is_template: name = index.schema.locus_columns[0] field_type = graphql.GraphQLID else: name = 'locus' field_type = graphql.GraphQLString #field_type = LocusInput # add the locus field; it's required args[name] = graphql.GraphQLNonNull(field_type) return obj_type, args
def visit_conversion( self, tp: AnyType, conversion: Optional[Conv], dynamic: bool, next_conversion: Optional[AnyConversion] = None, ) -> TypeFactory[GraphQLTp]: if not dynamic and self.is_id(tp) or tp == ID: return TypeFactory(lambda *_: graphql.GraphQLNonNull(self.id_type)) factory = super().visit_conversion(tp, conversion, dynamic, next_conversion) if not dynamic: factory = factory.merge(get_type_name(tp), get_schema(tp)) if get_args(tp): factory = factory.merge(schema=get_schema(get_origin(tp))) return factory # type: ignore
def arguments(self, definition: Optional[Dict]) -> Optional[GraphQLArgumentMap]: result: GraphQLArgumentMap = dict() if not definition or not isinstance(definition, (list, tuple)): return None for arg in definition: if not isinstance(arg, (Argument, ArgumentList)): continue mapped_type = self.map_input(arg.type) if arg.required: mapped_type = graphql.GraphQLNonNull(mapped_type) arg_name = snake_to_camel(arg.name, False) if self.camelcase else arg.name result[arg_name] = graphql.GraphQLArgument( mapped_type, description=arg.description ) return result
def visit_with_schema( self, cls: AnyType, ref: Optional[str], schema: Optional[Schema]) -> Thunk[graphql.GraphQLType]: if self.is_id(cls): return graphql.GraphQLNonNull(graphql.GraphQLID) if is_hashable(cls) and not self.is_extra_conversions(cls): ref, schema = ref or get_ref(cls), merge_schema( get_schema(cls), schema) else: schema, ref = None, None ref_save, schema_save, non_null_save = self._ref, self._schema, self._non_null self._ref, self._schema, self._non_null = ref, schema, True try: result = super().visit(cls) non_null = self._non_null return lambda: exec_thunk(result, non_null=non_null) except MissingRef: raise TypeError(f"Missing ref for type {cls}") finally: self._ref, self._schema = ref_save, schema_save self._non_null = non_null_save
import typing as t import graphql as g from handofcats import as_command from dictknife import loading Person = g.GraphQLObjectType( "Person", lambda: { "name": g.GraphQLField(g.GraphQLNonNull(g.GraphQLString)), "age": g.GraphQLField(g.GraphQLNonNull(g.GraphQLInt)), "nickname": g.GraphQLField(g.GraphQLString), }, ) query_type = g.GraphQLObjectType( "Query", lambda: { "person": g.GraphQLField( Person, args={"name": g.GraphQLArgument(g.GraphQLString)}, ) }, ) Person = t.Dict[str, t.Any] class Root: def __init__(self, data): self.data = data
def NNList(t): return graphql.GraphQLNonNull( graphql.GraphQLList(graphql.GraphQLNonNull(t)))
def _sql_column_to_graphql_type(column): nullable_type = _sql_type_to_graphql_type(column.type) if getattr(column, "nullable", True): return nullable_type else: return graphql.GraphQLNonNull(nullable_type)
import graphql from graphql.utilities import print_schema Person = graphql.GraphQLObjectType( "Person", lambda: { "name": graphql.GraphQLField(graphql.GraphQLNonNull(graphql.GraphQLString, )), }, ) Query = graphql.GraphQLObjectType( "Query", lambda: { "people": graphql.GraphQLField( graphql.GraphQLNonNull(graphql.GraphQLList(Person))) }, ) schema = graphql.GraphQLSchema(Query) print(print_schema(schema)) # or graphql.print_schema(schema)
def resolve_counter(root: float, info: graphql.GraphQLResolveInfo, ceil: int): # pylint: disable=W0613, unused-argument return f"{root} :: {info.operation.name.value}" schema = graphql.GraphQLSchema( query=graphql.GraphQLObjectType( name="RootQueryType", fields={ "name": graphql.GraphQLField( graphql.GraphQLString, resolve=resolve_name, args={ "title": graphql.GraphQLArgument( graphql.GraphQLNonNull(graphql.GraphQLString) ) }, ) }, ), subscription=graphql.GraphQLObjectType( name="RootSubscriptionType", fields={ "counter": graphql.GraphQLField( graphql.GraphQLString, resolve=resolve_counter, subscribe=subscribe_counter, args={ "ceil": graphql.GraphQLArgument( graphql.GraphQLNonNull(graphql.GraphQLInt)
def test_mapping_int(): assert is_equal_type( MAPPER.map(int), graphql.GraphQLNonNull(graphql.GraphQLInt) )