Exemple #1
0
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)
Exemple #2
0
    def __init__(self, **kwargs):
        assert 'type' in kwargs, f'ListMixin requires "type" kwarg, kwargs={kwargs}'

        self.many = kwargs.pop('many', False)
        assert isinstance(
            self.many, bool), f'many has to be of type bool, not {self.many}'
        if self.many:
            kwargs.update(type=graphql.GraphQLList(kwargs.get('type')))
        super().__init__(**kwargs)
    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))
Exemple #4
0
def ql_type(parent_name, field, xs):
    """
    Returns a Graphene field type for all values of xs. It assumes
    every item in xs is the same type or None.
    """
    all_types = set(
        [type(x) for x in xs if x is not None and x is not float('nan')])

    # handle a special case of floats being parsed as integers
    if all_types == set([int, float]):
        all_types = set([float])

    # there should only be one type per field
    if len(all_types) > 1:
        assert False, f'Heterogenous field type: {parent_name}/{field} ({all_types})'

    # get the only type
    this_type = all_types.pop()

    # dictionaries are an object type that needs defined
    if this_type == dict:
        return build_object_type(f'{parent_name}{field.capitalize()}', xs)

    # if the base type is a list, wrap the base type
    if this_type == list:
        return graphql.GraphQLList(
            ql_type(parent_name, field, [y for ys in xs for y in ys]))

    # scalar type
    if this_type == bool:
        return graphql.GraphQLBoolean
    elif this_type == int:
        return graphql.GraphQLInt
    elif this_type == float:
        return graphql.GraphQLFloat
    elif this_type == str:
        return graphql.GraphQLString

    # unknown, or can't be represented
    raise ValueError(f'Cannot define GraphQL type for {field}')
Exemple #5
0
 def collection(self, cls: Type[Collection],
                value_type: AnyType) -> TypeFactory[GraphQLTp]:
     return TypeFactory(
         lambda *_: graphql.GraphQLList(self.visit(value_type).type))
Exemple #6
0
def NNList(t):
    return graphql.GraphQLNonNull(
        graphql.GraphQLList(graphql.GraphQLNonNull(t)))
Exemple #7
0
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)
Exemple #8
0
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 _transform_list(t, ctx):
    return graphql.GraphQLList(ctx.transformer.transform(t.__args__[0]))
Exemple #10
0
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)},
        )
    },
)


class Root:
    def __init__(self, data):
        self.data = data

    def people(self, info, *, order_by):
        if order_by == "name_DESC":
            return sorted(self.data["people"],
                          key=lambda d: d["name"],
                          reverse=True)
Exemple #11
0
 def collection(self, cls: Type[Collection],
                value_type: AnyType) -> Thunk[graphql.GraphQLType]:
     value_thunk = self.visit(value_type)
     return lambda: graphql.GraphQLList(exec_thunk(value_thunk))