def to_graphql_field(graph_field): return graphql.GraphQLField( type_=to_graphql_type(graph_field.type), args=iterables.to_dict((snake_case_to_camel_case(param.name), to_graphql_argument(param)) for param in graph_field.params), )
def build_schema(config, engine, subset=None): """ Build the object types for all the indexes. Subset is a list of index names that the schema should include. If no subset is provided, then all indexes are built and added to the schema. """ fields = {} for i in Index.list_indexes(engine): if not subset or i.name in subset: try: output_type, args = build_index_type(config, engine, i) resolver = ql_resolver(config, engine, i) # create the field for this table, with arguments and resolver fields[f'{i.table.name}'] = graphql.GraphQLField( graphql.GraphQLList(output_type), args=args, resolve=resolver, ) except (ValueError, AssertionError) as ex: logging.error('%s; skipping %s...', str(ex), i.name) # construct the query object for the root object type root = graphql.GraphQLObjectType('Query', fields) # build the schema return graphql.GraphQLSchema(query=root)
def deref_merged_field(merged_attr: str, field: graphql.GraphQLField) -> graphql.GraphQLField: def resolve(obj, info, **kwargs): return field.resolve(getattr(obj, merged_attr), info, **kwargs) return graphql.GraphQLField(**ChainMap(dict( resolve=resolve), field.to_kwargs()))
def to_graphql_field(graph_field): return graphql.GraphQLField( type=to_graphql_type(graph_field.type), args=iterables.to_dict( (param.name, to_graphql_argument(param)) for param in graph_field.params ), )
def field_from_fn(mapper, fn_desc): sig = signature(fn_desc.fn) if sig.return_annotation is Signature.empty: raise ValueError('graphql functions must provide return type') result_type = mapper.map(sig.return_annotation) arg_types = { param.name: arg_from_parameter(mapper, param) for param in sig.parameters.values() } return graphql.GraphQLField(result_type, args=arg_types, resolve=make_resolver(fn_desc.fn))
def _field(self, field: ObjectField) -> Lazy[graphql.GraphQLField]: field_name = field.name partial_serialize = self._field_serialization_method(field) @self._wrap_resolve def resolve(obj, _): return partial_serialize(getattr(obj, field_name)) factory = self.visit_with_conv(field.type, field.serialization) return lambda: graphql.GraphQLField( factory.type, None, resolve, description=get_description(field.schema, field.type), deprecation_reason=get_deprecated(field.schema, field.type), )
def _field(self, field: ObjectField) -> Tuple[str, Lazy[graphql.GraphQLField]]: alias = field.apply_aliaser(self.aliaser) if field.resolve is not None: resolve = field.resolve else: resolve = lambda obj, _: getattr(obj, field.name) # noqa: E731 field_type = self.visit_with_conversions(field.type, field.conversions) args = None if field.parameters is not None: args = {} for param in field.parameters: default = graphql.Undefined if param.default not in { Parameter.empty, Undefined, graphql.Undefined }: with suppress(Exception): default = serialize(param.default) def arg_thunk( arg_thunk=self.input_builder.visit(param.type), default=default, out_name=param.name, ) -> graphql.GraphQLArgument: arg_type = exec_thunk(arg_thunk) if (not isinstance(arg_type, graphql.GraphQLNonNull) and default is None): default = graphql.Undefined return graphql.GraphQLArgument(arg_type, default, out_name=out_name) args[self.aliaser(param.name)] = arg_thunk return alias, lambda: graphql.GraphQLField( exec_thunk(field_type), {name: arg() for name, arg in args.items()} if args else None, resolve, field.subscribe, field.description, field.deprecated, )
def build_object_type(name, objs): """ Create the object type of a given set of objects, which is the union of all fields across the objects. """ all_columns = set([k for obj in objs for k in obj.keys()]) # transpose the objects into columns of values columns = {} for k in all_columns: if not ql_is_valid_field(k): logging.warning( '%s is not a valid GraphQL field name; skipping...', k) else: columns[k] = [obj[k] for obj in objs if k in obj] # determine the type of each field (ignore nulls) fields = {} for field_name, xs in columns.items(): this_type = ql_type(name, field_name, xs) fields[field_name] = graphql.GraphQLField(this_type) # build the final object return graphql.GraphQLObjectType(name, fields)
import graphql as g from handofcats import as_command from dictknife import loading person_order_input_enum = g.GraphQLEnumType( "PersonOrderInput", { "name_ASC": g.GraphQLEnumValue("name_ASC"), "name_DESC": g.GraphQLEnumValue("name_DESC"), }, ) 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: { "people": g.GraphQLField( g.GraphQLList(Person), args={"order_by": g.GraphQLArgument(person_order_input_enum)}, ) }, )
def _resolver(self, field: ResolverField) -> Lazy[graphql.GraphQLField]: resolve = self._wrap_resolve( resolver_resolve( field.resolver, field.types, self.aliaser, self.input_builder.default_conversion, self.default_conversion, )) args = None if field.parameters is not None: args = {} for param in field.parameters: default: Any = graphql.Undefined param_type = field.types[param.name] if is_union_of(param_type, graphql.GraphQLResolveInfo): break param_field = ObjectField( param.name, param_type, param.default is Parameter.empty, field.metadata.get(param.name, empty_dict), default=param.default, ) if param_field.required: pass # Don't put `null` default + handle Undefined as None # also https://github.com/python/typing/issues/775 elif param.default in {None, Undefined}: param_type = Optional[param_type] # param.default == graphql.Undefined means the parameter is required # even if it has a default elif param.default not in {Parameter.empty, graphql.Undefined}: try: default = serialize( param_type, param.default, fall_back_on_any=False, check_type=True, ) except Exception: param_type = Optional[param_type] arg_factory = self.input_builder.visit_with_conv( param_type, param_field.deserialization) description = get_description(param_field.schema, param_field.type) def arg_thunk( arg_factory=arg_factory, default=default, description=description) -> graphql.GraphQLArgument: return graphql.GraphQLArgument(arg_factory.type, default, description) args[self.aliaser(param_field.alias)] = arg_thunk factory = self.visit_with_conv(field.type, field.resolver.conversion) return lambda: graphql.GraphQLField( factory.type, # type: ignore {name: arg() for name, arg in args.items()} if args else None, resolve, field.subscribe, field.description, field.deprecated, )
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)
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
import graphql as g Person = g.GraphQLObjectType( "Person", lambda: { "name": g.GraphQLField(g.GraphQLNonNull(g.GraphQLString)), "age": g.GraphQLField(g.GraphQLNonNull(g.GraphQLInt)), "nickname": g.GraphQLField(g.GraphQLString), }, ) def get_person(root, _info): return root["person"] query_type = g.GraphQLObjectType( "Query", lambda: {"person": g.GraphQLField(Person, resolve=get_person)}, ) schema = g.GraphQLSchema(query_type) q = """ { person { name, age, nickname } } """ data = {"person": {"name": "foo", "age": 20, "nickname": "F"}} print(g.graphql_sync(schema, q, data))
import graphql as g Person = g.GraphQLObjectType( "Person", lambda: { "name": g.GraphQLField(g.GraphQLNonNull(g.GraphQLString)), "age": g.GraphQLField(g.GraphQLNonNull(g.GraphQLInt)), "nickname": g.GraphQLField(g.GraphQLString), "father": g.GraphQLField(Person), "mother": g.GraphQLField(Person), }, ) class Root: def __init__(self, data): self.data = data def person(self, _info): return self.data["person"] query_type = g.GraphQLObjectType( "Query", lambda: {"person": g.GraphQLField(Person)}, ) schema = g.GraphQLSchema(query_type) q = """ { person { name, age, nickname, father, mother } } """
import graphql as g from handofcats import as_command from minidb import Table 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: {"people": g.GraphQLField(g.GraphQLList(Person))}, ) class Root: def __init__(self, tables): self.tables = tables def people(self, info): return self.tables["people"].find_all() schema = g.GraphQLSchema(query_type) @as_command
def to_field(t, ctx: TransformContext): params = ("args", "resolve", "subscribe", "description", "deprecation_reason") return graphql.GraphQLField(t, **{k: ctx[k] for k in params if k in ctx})
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(