class User(ObjectType): id = ID() created = DateTime() modified = DateTime() name = String() email = String() profile_picture = String()
def __init_subclass_with_meta__( cls, output=None, input_fields=None, arguments=None, name=None, **options ): cls.model = graphene.Field(cls.Options.model) cls.created = graphene.Boolean(default_value = False) cls.updated = graphene.Boolean(default_value=False) cls.deleted = graphene.Boolean(default_value=False) model_fields = convert_fields(cls) model_fields['action'] = String(required=True) model_fields.update() input_class = getattr(cls, "Input", None) base_name = re.sub("Payload$", "", name or cls.__name__) assert not output, "Can't specify any output" assert not arguments, "Can't specify any arguments" bases = (InputObjectType,) if input_class: bases += (input_class,) if not input_fields: input_fields = {} cls.Input = type( "{}Input".format(base_name), bases, dict( **model_fields,**input_fields, client_mutation_id=String(name="clientMutationId") ), ) arguments = OrderedDict( input=cls.Input(required=True) # 'client_mutation_id': String(name='clientMutationId') ) mutate_and_get_payload = getattr(cls, "mutate_and_get_payload", None) if cls.mutate and cls.mutate.__func__ == ModelMutation.mutate.__func__: assert mutate_and_get_payload, ( "{name}.mutate_and_get_payload method is required" " in a ClientIDMutation." ).format(name=name or cls.__name__) if not name: name = "{}Payload".format(base_name) super(ModelMutation, cls).__init_subclass_with_meta__( output=None, arguments=arguments, name=name, **options ) cls._meta.fields["client_mutation_id"] = Field(String, name="clientMutationId")
class Comment(ObjectType): class Meta: interfaces = (Node, ) id = ID(required=True) created = DateTime() modified = DateTime() user = Field('User') voyage = Field('Voyage') text = String() chapter = String()
class UpdateAlimentationInput(graphene.InputObjectType): """ Classe responsável pelos campos de atualização da alimentação do pet. """ qtd = String( required=False, description="Quantidade de ração diaria (SMALL, MEDIUM, BIG).") food = String(required=False, description="Nome da ração utilizada para alimentar o pet.") frequency = PositiveIntegerField( required=False, description="Quantidade de vezes que deve alimentar o animal por dia.") observations = String(required=False, description="Observações importantes.")
class Voyage(ObjectType): class Meta: interfaces = (Node, ) id = ID(required=True) created = DateTime() modified = DateTime() name = String() media = Field('Media') owner = Field('User') members = List('User') comment_counts = GenericScalar() def resolve_comment_counts(root, info): # Initialize a dictionary with 0 comment count per chapter base_dict = dict.fromkeys(root.chapters, 0) counts = (db.session.query(Comment.chapter, func.count( Comment.id)).filter(Comment.voyage == root).group_by( Comment.chapter)).all() base_dict.update(dict(counts)) return base_dict
class Media(ObjectType): class Meta: interfaces = (Node, ) id = ID(required=True) created = DateTime() modified = DateTime() series = String() order = Int() name = String() type = String() chapters = List(String) external_url = String()
class QueryPet(graphene.ObjectType): """ Tipo especial de consulta que obtem dados do servidor. """ collection = graphene.List( PetType, description="Listar todos os pets de um usuário do pet guard.", identify=String(required=True, description="Identificador do usuário."), search=String( description= "Procurar um pet pelo seu nome ou pelos dados da ong na qual ele pertence (nome, email ou cnpj)." ), kind=String(description="Filtrar os pets do tipo DOG ou CAT."), is_adoption=Boolean( description="Filtra somente os pets que estão em adoção."), is_adopted=Boolean(description="Filtra por pets adotados."), skip=Int(description="Pula os primeiros N usuários."), first=Int(description="Pega os primeiros N usuários após o skip.")) instance = graphene.Field( PetType, description="Pegar os dados de um pet especifico do pet guard.", identify=String(required=True, description="Identificador do usuário."), pet_id=String(required=True, description="Identificador do pet.")) def resolve_collection(self, info, identify, **kwargs): """ Cada campo é manipulado por meio de resolvers, que retornam um valor. """ pets = ListPetResolver(identify, kwargs).get_result() return pets def resolve_instance(self, info, identify, pet_id): """ Pega um usuário especifico """ pet = FetchPetResolver(identify, pet_id).get_result() return pet
class WagtailImageNode(DjangoObjectType): class Meta: model = Image # Tags would need a separate converter, so let's just # exclude it at this point to keep the scope smaller exclude_fields = ['tags'] url = String() def resolve_url(self, info): return self.file.url
class VoyageQuery(object): voyage = Field( 'Voyage', voyage_id=ID(name='id', required=True), ) voyages = ConnectionField('VoyageConnection') comments_for_voyage = ConnectionField( 'CommentConnection', voyage_id=ID(name='id', required=True), chapter=String(), ) def resolve_voyage(root, info, voyage_id): return Voyage.query.get(voyage_id) def resolve_voyages(root, info): return Voyage.query def resolve_comments_for_voyage(root, info, voyage_id, chapter=None): voyage = Voyage.query.get(voyage_id) if voyage is None: raise QueryException('Voyage not found') membership = (Membership.query.filter( Membership.voyage == voyage, Membership.user == current_user, )).first() if membership is None: raise QueryException('Voyage not found') current_chapter_index = voyage.chapters.index( membership.current_chapter) allowed_chapters = voyage.chapters[:current_chapter_index + 1] # Include the current chapter with + 1 comments = (Comment.query.filter( Comment.voyage == voyage, Comment.chapter.in_(allowed_chapters), )) if chapter: if chapter not in voyage.chapters: QueryException( 'Invalid chapter ({}) for the voyage'.format(chapter)) comments = comments.filter(Comment.chapter == chapter) return comments
class UpdatePetInput(graphene.InputObjectType): """ Classe responsável pelos campos de atualização do pet """ name = String(required=False, description="Nome do animal de estimação.") kind = String(required=False, description="Tipo do animal de estimação (CAT, DOG).") sex = String(required=False, description="Sexo do animal de estimação (FEMALE, MALE).") height = String( required=False, description="Porte do animal de estimação (SMALL, MEDIUM, BIG).") temperament = String( required=False, description= "Temperamento do animal de estimação (DOCILE, FRIENDLY, BRAVE).") age = PositiveIntegerField(required=False, description="Idade do animal de estimação.") breed = String(required=False, description="Raça do animal de estimação.") photo = Upload(required=False, description="Foto do animal de estimação.") phone = PhoneField( required=False, description="Telefone para contato caso encontre o dono.") weight = PositiveFloatField(required=False, description="Peso do animal de estimação.") description = String( required=False, description= "Breve descrição do comportamento do animal ou outras informações.") alimentation = Field( UpdateAlimentationInput, description="Dados relacionados a alimentação do pet.", required=False) special_cares = Field( UpdateSpecialCaresInput, description="Dados relacionados a cuidados especiais do pet.", required=False)
class UpdateSpecialCaresInput(graphene.InputObjectType): """ Classe responsável pelos campos de atualização de cuidados especiais do pet. """ veterinary_frequency = PositiveIntegerField( required=False, description= "Quantidade de vezes que o animal vai ao veterinário por mês.") bathing_frequency = PositiveIntegerField( required=False, description="De quantos em quantos dias o animal toma banho.") diseases = String( required=False, description="Descrição sobre os problemas de saúde que o animal tem.") shear_type = String(required=False, description="Tipo de tosa.") shear_frequency = PositiveIntegerField( required=False, description="De quantos em quantos dias o animal é tosado.") deworming = String(required=False, description="Nome da última vermifugação tomada.") deworming_date = DateField(required=False, description="Data da última vermifugação.") vaccination = String(required=False, description="Nome da última vacinação tomada") vaccination_date = DateField(required=False, description="Data da última vacinação.") is_castrated = Boolean(required=False, description="O animal é castrado?") last_estro = DateField(required=False, description="Data do último CIO.") observations = String(required=False, description="Observações importantes.") veterinary_feedback = String( required=False, description= "Feedbacks para uso veterinário caso alguém leve o pet para o veterinário e não tenha as informações necessárias." )
class Letter(ObjectType): class Meta: interfaces = (Node, ) letter = String()
def convert_binary(field, registry=None): """Convert BinaryField to String.""" return String()
class Arguments: media_id = ID(required=True, description='ID of the media that this voyage is for') name = String(required=True, description='Name of the voyage')
class Arguments: voyage_id = ID(name='id', required=True, description='ID of the voyage to invite to') email = String(required=True, description='Email of the user to invite')
class EdgeBase(object): node = Field(_node, description="The item at the end of the edge") cursor = String(required=True, description="A cursor for use in pagination")
def __new__(cls, name, bases, attrs): # Also ensure initialization is only performed for subclasses of # Mutation if not is_base_type(bases, ClientIDMutationMeta): return type.__new__(cls, name, bases, attrs) defaults = dict( name=name, description=attrs.pop('__doc__', None), interfaces=(), local_fields=None, permission_classes=(), throttle_classes=(), # for Django Model Permissions model=None, # for permissions method=None, # 'CREATE', 'UPDATE', 'DELETE' only this 3 accepted form_class=None, lookup_field='pk', lookup_kwarg=None ) options = Options( attrs.pop('Config', None), **defaults ) if options.model is not None: assert is_valid_django_model(options.model), ( 'You need to pass a valid Django Model in {}.Meta, received "{}".' ).format(name, options.model) input_class = attrs.pop('Input', None) base_name = re.sub('Payload$', '', name) if 'client_mutation_id' not in attrs: attrs['client_mutation_id'] = String(name='clientMutationId') cls = ObjectTypeMeta.__new__(cls, '{}Payload'.format(base_name), bases, dict(attrs, _meta=options)) mutate_and_get_payload = getattr(cls, 'mutate_and_get_payload', None) if cls.mutate and cls.mutate.__func__ == ClientIDMutation.mutate.__func__: assert mutate_and_get_payload, ( "{}.mutate_and_get_payload method is required" " in a ClientIDMutation." ).format(name) input_attrs = {} bases = () if not input_class: input_attrs = {} elif not issubclass(input_class, AbstractType): input_attrs = props(input_class) else: bases += (input_class, ) input_attrs['client_mutation_id'] = String(name='clientMutationId') # If method is update and delete add id to input attrs if options.method is not None and options.method.upper() in ['UPDATE', 'DELETE']: input_attrs['id'] = String(name='id', required=True) cls.Input = type('{}Input'.format(base_name), bases + (InputObjectType,), input_attrs) cls.Field = partial(Field, cls, resolver=cls.mutate, input=Argument(cls.Input, required=True)) return cls
class Arguments: voyage_id = ID(name='id', required=True, description='ID of the voyage to comment in') chapter = String(required=True, description='The chapter to comment on') text = String(required=True, description='The comment')