Example #1
0
class Rider(ObjectType):
    id = Int(required=True)
    firstName = String(required=True)
    lastName = String(required=True)
    email = String(required=True)
    birthday = DateTime(required=True)
    teams = List(NonNull(Team), required=True)
    rides = List(NonNull(Ride), required=True)

    def resolve_teams(rider, info):
        db_cursor.execute(
            """
            SELECT team.id, website, contactEmail, since FROM team
            INNER JOIN teamMember tm
              ON team.id = tm.teamId
            WHERE tm.cyclistId = %(rider_pk)s 
            """, {"rider_pk": rider['rider_id']})
        return [Rider(**row_data) for row_data in db_cursor.fetchall()]

    def resolve_rides(rider, info):
        db_cursor.execute(
            """
            SELECT ride.cyclistId, trailId, date, distance FROM ride
            INNER JOIN rider 
              ON rider.id = ride.cyclistId
            WHERE ride.cyclistId = %(rider_pk)s 
            """, {"rider_pk": rider['rider_id']})
        return [Rider(**row_data) for row_data in db_cursor.fetchall()]
Example #2
0
    def __init__(self,
                 _type,
                 ordering="-created",
                 cursor_query_param="cursor",
                 *args,
                 **kwargs):
        kwargs.setdefault("args", {})

        self.page_size = graphql_api_settings.DEFAULT_PAGE_SIZE
        self.page_size_query_param = "page_size" if not self.page_size else None
        self.cursor_query_param = cursor_query_param
        self.ordering = ordering
        self.cursor_query_description = "The pagination cursor value."
        self.page_size_query_description = "Number of results to return per page."

        kwargs[self.cursor_query_param] = NonNull(
            String, description=self.cursor_query_description)

        if self.page_size_query_param:
            if not self.page_size:
                kwargs[self.page_size_query_param] = NonNull(
                    Int, description=self.page_size_query_description)
            else:
                kwargs[self.page_size_query_param] = Int(
                    description=self.page_size_query_description)

        super(CursorPaginationField, self).__init__(List(_type), *args,
                                                    **kwargs)
Example #3
0
class Company(ObjectType):
    id = ID(required=True)
    name = String(required=True)

    address_line1 = String(required=False)
    address_line2 = String(required=False)
    address_line3 = String(required=False)

    postal_code = String(required=True)
    city = String(required=True)

    industry = Field(Industry, required=False)
    contact = Field(CompanyContact, required=True)

    # lazy
    demands = List(lambda: NonNull(Demand), resolver=demands_by_company)
    supplies = List(lambda: NonNull(Supply), resolver=supplies_by_company)

    # def resolve_contact(root, info):
    #     if root.

    def resolve_industry(root, info):
        if root.industry_id is None:
            return []

        return g.industry_loader.load(root.industry_id)
Example #4
0
 class Input(object):
     """
     We need the ticker, bucket and quantity to create the connection
     """
     stock_id = NonNull(ID)
     bucket_id = NonNull(ID)
     quantity = NonNull(Float)
Example #5
0
 class Input(object):
     """
     We need the description and the bucket as input
     """
     desc = NonNull(String)
     bucket_id = NonNull(ID)
     is_good = NonNull(Boolean)
Example #6
0
class PrivacySettings(MongoengineObjectType):
    class Meta:
        model = PrivacySettingsModel

    users_access = NonNull(List(NonNull(UserPrivacySettings)))
    visibility = VisibilityEnum(required=True)
    public_access_type = AccessEnum(required=True)
Example #7
0
class CreatePerson(Mutation):
    """Create a new person.
    """
    # class Meta(object):
    #     interfaces = (Person, )  # TODO: REFACTOR!
    id = NonNull(ID, description="Unique ID.")
    name = NonNull(String, description="Name, full name or username.")
    age = Field(Int, description="Age in years.")

    # person = Field(Person)  # TODO

    class Arguments:
        name = Argument(String,
                        required=True,
                        description="Name, full name or username.")
        age = Argument(Int, default_value=-1, description="Age in years.")

    def mutate(root, info, name, **kwargs):
        id = uuid.uuid4()
        age = kwargs.get("age")
        person = Person(id=id, name=name, age=age)

        faux_database[id] = person

        return CreatePerson(id=id, name=name, age=age)
Example #8
0
 class Arguments(object):
     """
     Arguments to create a trade. Right now it's only ticker and quantity.
     """
     id_value = NonNull(String)
     quantity = NonNull(Int)
     account_name = NonNull(String)
Example #9
0
class UpdateSamplesMutation(Mutation):
    class Arguments:
        samples = NonNull(List(NonNull(SampleInput)))

    committed = NonNull(Boolean)
    diff = NonNull(SamplesDiff)

    @classmethod
    def mutate(cls, root, info, samples, *args, **kwargs):
        committed = False
        with transaction.atomic():
            # retrieve samples from db
            samples_db = models.Sample.objects.all()

            # validate (with renamed fk field)
            samples_to_compare = deserialise_samples(samples)

            # compute diff
            diff = diff_samples(samples_db, samples_to_compare)

            # only update if there are no missing institutions
            if len(diff["missing_institutions"]) == 0:
                # clear samples table in db
                samples_db.delete()

                # insert new entries
                models.Sample.objects.bulk_create(samples_to_compare)

                committed = True

        return UpdateSamplesMutation(committed=committed, diff=diff)
Example #10
0
 class Arguments(object):
     """
     We need quantity, account id and bucket id
     """
     quantity = NonNull(Float)
     trading_acc_id = NonNull(ID)
     bucket_id = NonNull(ID)
Example #11
0
class GTradingAccount(DjangoObjectType):
    """
    Exposing the whole TradingAccount to GraphQL
    """
    total_value = NonNull(Float)
    available_cash = NonNull(Float)

    class Meta(object):
        """
        Meta Model for TradingAccount
        """
        model = TradingAccount
        interfaces = (relay.Node, )

    @staticmethod
    def resolve_total_value(data, _info, **_args):
        """
        Returns the total value that the account currently holds
        """
        return data.total_value()

    @staticmethod
    def resolve_available_cash(data, _info, **_args):
        """
        Returns the amount of cash the user has available
        """
        return data.available_cash(False)
Example #12
0
class Rocket_Type(ObjectType):
    rocket_id = NonNull(String)
    rocket_name = NonNull(String)
    rocket_type = NonNull(String)
    first_stage = NonNull(First_Stage_Type)
    second_stage = NonNull(Second_Stage_Type)
    fairings = Field(Fairings)
Example #13
0
 class Input(object):
     """
     We only need the name of the new bucket to create it
     """
     name = NonNull(String)
     investment = NonNull(Float)
     public = NonNull(Boolean)
Example #14
0
class Query(ObjectType):
    user = Field(githubUserType, username=NonNull(String))

    repo = List(RepositoryType, username=NonNull(String))

    project = List(ProjectType, username=NonNull(String))

    def resolve_user(self, info, username):
        cache_key = 'user-{}'.format(username)
        cached_user = cache.get(cache_key)
        if cached_user:
            return convertJsonToObject(cached_user, "user")

        return resolveUser(username)

    def resolve_repo(self, info, username):
        cache_key = 'repo-{}'.format(username)
        cached_repo = cache.get(cache_key)
        if cached_repo:
            return convertJsonToObject(cached_repo, "user")

        return resolveUserRepos(username)

    def resolve_project(self, info, username):
        cache_key = 'project-{}'.format(username)
        cached_project = cache.get(cache_key)
        if cached_project:
            return convertJsonToObject(cached_project, "project")

        return resolveUserProject(username)
Example #15
0
class SlotType(ObjectType):
    class Meta:
        name = "Slot"

    id = NonNull(ID)
    talk = Field(TalkType)
    session = NonNull(lambda: SessionType)
    room = NonNull(RoomType)
Example #16
0
class CountryQuery(object):
    countries = NonNull(List(NonNull(CountryType)))

    def resolve_countries(root, info):
        return [{
            "code": key,
            "name": value
        } for key, value in dict(countries).items()]
class UserInfo(ObjectType):
    class Meta:
        interfaces = (UserInterface, )

    follower_count = NonNull(Int)
    following_count = NonNull(Int)
    biography = NonNull(String)
    feed = Field(NonNull(Feed))
Example #18
0
class GridType(ObjectType):
    class Meta:
        name = "Grid"

    sessions = NonNull(List(NonNull(SessionType)))

    @staticmethod
    def resolve_sessions(parent, info):
        return parent["sessions"].order_by("start_time")
Example #19
0
    def test_handles_non_null_list_of_non_null_nested_type(self):
        InnerType = create_obj_type_mock(Field(String))
        OuterType = create_obj_type_mock(NonNull(List(NonNull(InnerType))))
        data = {'field': [{'field': 'a'}, {'field': 'b'}]}
        stitched = stitch(OuterType)(data)

        outer = stitched.resolve_field(None)
        print(outer)
        assert [x.resolve_field(None) for x in outer] == ['a', 'b']
Example #20
0
class SpeakerType(ObjectType):
    class Meta:
        name = "Speaker"

    id = NonNull(ID)
    name = NonNull(String)

    @staticmethod
    def resolve_name(parent: User, info):
        return parent.username
Example #21
0
class Person(ObjectType):
    id = NonNull(ID)
    first_name = NonNull(String)
    last_name = NonNull(String)
    age = NonNull(Int)
    profile_url = NonNull(String)

    @staticmethod
    def resolve_profile_url(root: 'Person', info):
        return info.context.loaders.person_profile_pictures.load(root.id)
 class Arguments:
     username = String(required=True)
     taskid = Int(required=True)
     title = String(required=True)
     description = String()
     starttime = types.DateTime()
     endtime = types.DateTime()
     priority = String()
     preqtaskid = List(NonNull(Int))
     assignedto = NonNull(List(NonNull(String)))
 class Arguments:
     assignedby = String(required=True)
     assignedto = NonNull(List(NonNull(String)))
     projectid = Int(required=True)
     title = String(required=True)
     description = String()
     startdate = types.DateTime()
     enddate = types.DateTime()
     priority = String()
     preqtaskid = List(NonNull(Int))
Example #24
0
class Page(ObjectType):
    name = NonNull(String)
    title = NonNull(String)
    contenttype = PageType
    content = String

    def __init__(self, name, title, contenttype):
        self.name = name
        self.title = title
        self.contenttype = contenttype
        self.content = ''
Example #25
0
class Engines(ObjectType):
    number = NonNull(Int)
    type = NonNull(String)
    version = NonNull(String)
    layout = NonNull(String)
    engine_loss_max = NonNull(Int)
    propellant_1 = NonNull(String)
    propellant_2 = NonNull(String)
    thrust_sea_level = NonNull(Thrust_Sea_Level)
    thrust_vacuum = NonNull(Thrust_Vacuum)
    thrust_to_weight = NonNull(Float)
Example #26
0
class Payload(ObjectType):
    payload_id = NonNull(String)
    reused = NonNull(Boolean)
    nationality = NonNull(String)
    manufacturer = NonNull(String)
    payload_type = NonNull(String)
    payload_mass_kg = NonNull(Int)
    payload_mass_lbs = NonNull(Int)
    orbit = NonNull(String)
    orbit_params = NonNull(Orbit_Params)
    customers = List(NonNull(String))
    norad_id = List(Int)
Example #27
0
class Chat(DjangoObjectType):
    page_limit = 256

    class Meta:
        model = models.Chat
        exclude_fields = ('password', )

    log_list = graphene.Field(LogList,
                              password=graphene.String(),
                              page=graphene.Int(),
                              tag_id=graphene.String())
    has_password = NonNull(graphene.Boolean)
    counter = NonNull(graphene.Int)
    page_counter = NonNull(graphene.Int)

    @staticmethod
    def resolve_has_password(chat: models.Chat, info):
        return bool(chat.password)

    @staticmethod
    def resolve_page_counter(chat: models.Chat, info):
        return chat.all_log().count() % Chat.page_limit

    @staticmethod
    def resolve_log_list(chat: models.Chat,
                         info,
                         password='',
                         tag_id=None,
                         page=1):
        if page < 1:
            page = 1
        limit = Chat.page_limit
        offset = (page - 1) * Chat.page_limit
        tag_name = None
        if not chat.password or (chat.password and chat.validate(password)):
            query_set = chat.all_log()
            if tag_id:
                tag: Optional[models.Tag] = models.Tag.objects.filter(
                    id=int(tag_id), chat=chat).first()
                if tag:
                    query_set = tag.log_set.all()
            log_counter = query_set.count()
            log_list = LogList(tag_name=tag_name,
                               log_list=query_set[offset:offset + limit].all(),
                               total_page=log_counter // Chat.page_limit + 1)
            return log_list
        else:
            return None

    @staticmethod
    def resolve_counter(chat: models.Chat, info):
        return chat.log_count()
Example #28
0
class Post(ObjectType):
    """A text published by an author.
    """
    """
    type Post {
        id: ID!
        text: String!
        author: Person!
    }
    """
    id = NonNull(ID, description="Unique ID.")
    text = NonNull(String, description="UTF-8 content.")
    author = NonNull(Person, description="Text author.")
Example #29
0
class Person(ObjectType):
    """User which can author posts.
    """
    """
    type Person {
        id: ID!
        name: String!
        age: Int
        # posts: [Post!]!
    }
    """
    id = NonNull(ID, description="Unique ID.")
    name = NonNull(String, description="Name, full name or username.")
    age = Field(Int, description="Age in years.")
Example #30
0
class Query(ObjectType):
    articles = List(NonNull(lambda: Article))
    articles_with_author_age_provide = List(
        NonNull(lambda: ArticleThatProvideAuthorAge))

    def resolve_articles(self, info):
        return [Article(id=1, text='some text', author=User(id=5))]

    def resolve_articles_with_author_age_provide(self, info):
        return [
            ArticleThatProvideAuthorAge(id=1,
                                        text='some text',
                                        author=User(id=5))
        ]