Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Graphene resolver for an object that has no model

I'm trying to write a resolver that returns an object created by a function. It gets the data from memcached, so there is no actual model I can tie it to.

I think my main issue is I can't figure out what type to use and how to set it up. I'm using this in conjunction with Django, but I don't think it's a django issue (afaict). Here's my code so far:

class TextLogErrorGraph(DjangoObjectType):

    def bug_suggestions_resolver(root, args, context, info):
        from treeherder.model import error_summary
        return error_summary.bug_suggestions_line(root)

    bug_suggestions = graphene.Field(TypeForAnObjectHere, resolver=bug_suggestions_resolver)

Notice I don't know what type or field to use. Can someone help me? :)

like image 925
Cameron Avatar asked Jun 01 '17 15:06

Cameron


1 Answers

GraphQL is designed to be backend agnostic, and Graphene is build to support various python backends like Django and SQLAlchemy. To integrate your custom backend, simply define your models using Graphene's type system and roll out your own resolvers.

import graphene
import time

class TextLogEntry(graphene.ObjectType):

    log_id = graphene.Int()
    text = graphene.String()
    timestamp = graphene.Float()
    level = graphene.String()

def textlog_resolver(root, args, context, info):
    log_id = args.get('log_id') # 123
    # fetch object...
    return TextLogEntry(
        log_id=log_id,
        text='Hello World',
        timestamp=time.time(),
        level='debug'
    )

class Query(graphene.ObjectType):

    textlog_entry = graphene.Field(
        TextLogEntry,
        log_id=graphene.Argument(graphene.Int, required=True),
        resolver=textlog_resolver
    )


schema = graphene.Schema(
    query=Query
)

Example query with GraphiQL

like image 146
Ivan Choo Avatar answered Sep 21 '22 09:09

Ivan Choo