Esempio n. 1
0
    def mutate(cls, root, context, **kwargs):
        """
        Mutation logic is handled here
        """

        # 'before_insert' hooks won't work with db.session.bulk_save_objects
        # we need to find a way to get hooks to work with bulk_save_objects @todo

        records = []
        for data in kwargs.get('records', []):
            actual = Contact.query.get(data['uid'])

            if not actual:
                raise GraphQLError('Invalid id (%s)' % data['id'])

            c = Contact.get_object_from_graphql_input(data)

            for column_name, _ in inspect(Contact).attrs.items():
                if column_name == 'id':
                    continue
                if column_name not in data:
                    continue
                setattr(actual, column_name, getattr(c, column_name))
            db.session.add(actual)
            records.append(actual.id)
        try:
            db.session.commit()
            return cls(ok=True, ids=records)
        except Exception as e:
            raise GraphQLError(e.args)
Esempio n. 2
0
def measure_depth(node: Node, fragments: Dict[str, FragmentDefinition]):
    if isinstance(node, FragmentSpread):
        fragment = fragments.get(node.name.value)
        return measure_depth(node=fragment, fragments=fragments)

    elif isinstance(node, Field):
        if not node.selection_set:
            return 1

        depths = []
        for selection in node.selection_set.selections:
            depth = measure_depth(node=selection, fragments=fragments)
            depths.append(depth)

            if 1 + depth > settings.MAX_QUERY_DEPTH:
                raise GraphQLError("Query depth exceeded. Aborting")

        return 1 + max(depths)

    elif (isinstance(node, FragmentDefinition)
          or isinstance(node, OperationDefinition)
          or isinstance(node, InlineFragment)):
        depths = []
        for selection in node.selection_set.selections:
            depth = measure_depth(node=selection, fragments=fragments)
            depths.append(depth)

            if depth > settings.MAX_QUERY_DEPTH:
                raise GraphQLError("Query depth exceeded. Aborting")

        return max(depths)
    else:
        print(type(node))
        raise Exception("Unknown node")
Esempio n. 3
0
    def mutate(cls, root, context, **kwargs):
        """ 
        Mutation logic is handled here
        """

        # More details about synchronize_session options in SqlAlchemy
        # http://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.query.Query.delete

        query = Contact.query.filter(Contact.id.in_(kwargs.get('uids', [])))

        objs = []

        for obj in query:
            db.session.delete(obj)
            objs.append(obj)

        db.session.info['changes'] = {
            'created': [],
            'updated': [],
            'deleted': objs
        }
        try:
            db.session.commit()
            return cls(ok=True)

        except Exception as e:
            raise GraphQLError(e.args)
Esempio n. 4
0
def get_user_by_context(context: WSGIRequest):

    if not context.user.is_authenticated:
        raise GraphQLError('User is anonymous')

    token = context.headers['Authorization'].replace('Bearer ', '')
    user = get_user_by_token(token, context)
    return user
Esempio n. 5
0
def validate_depth(document: Document):

    fragments = get_fragments(document.definitions)
    queries = get_queries_and_mutations(document.definitions)

    for query in queries:
        depth = measure_depth(query, fragments)
        if depth > settings.MAX_QUERY_DEPTH:
            raise GraphQLError("Query depth exceeded. Aborting")
Esempio n. 6
0
    def mutate(cls, root, context, **kwargs):
        """
        Mutation logic is handled here
        """
        # 'before_insert' hooks won't work with db.session.bulk_save_objects
        # we need to find a way to get hooks to work with bulk_save_objects @todo

        objs = []

        for data in kwargs.get('records', []):
            c = Contact.get_object_from_graphql_input(data)
            db.session.add(c)
            objs.append(c)
        try:
            db.session.commit()
            return cls(ok=True, ids=[obj.id for obj in objs])
        except Exception as e:
            raise GraphQLError(e.args)