def define_generic_order_types(self): self._gql_ordertypes['directionEnum'] = GraphQLEnumType( 'directionEnum', values=OrderedDict( ASC=GraphQLEnumValue(), DESC=GraphQLEnumValue() ) ) self._gql_ordertypes['nullsOrderingEnum'] = GraphQLEnumType( 'nullsOrderingEnum', values=OrderedDict( SMALLEST=GraphQLEnumValue(), BIGGEST=GraphQLEnumValue(), ) ) self._gql_ordertypes['Ordering'] = GraphQLInputObjectType( 'Ordering', fields=OrderedDict( dir=GraphQLInputObjectField( GraphQLNonNull(self._gql_ordertypes['directionEnum']), ), nulls=GraphQLInputObjectField( self._gql_ordertypes['nullsOrderingEnum'], default_value='SMALLEST', ), ) )
def define_enums(self): self._gql_enums['directionEnum'] = GraphQLEnumType( 'directionEnum', values=OrderedDict( ASC=GraphQLEnumValue(), DESC=GraphQLEnumValue() ) ) self._gql_enums['nullsOrderingEnum'] = GraphQLEnumType( 'nullsOrderingEnum', values=OrderedDict( SMALLEST=GraphQLEnumValue(), BIGGEST=GraphQLEnumValue(), ) ) scalar_types = list( self.edb_schema.get_objects(modules=self.modules, type=s_scalars.ScalarType)) for st in scalar_types: if st.is_enum(self.edb_schema): name = self.get_gql_name(st.get_name(self.edb_schema)) self._gql_enums[name] = GraphQLEnumType( name, values=OrderedDict( (key, GraphQLEnumValue()) for key in st.get_enum_values(self.edb_schema) ) )
def define_enums(self): self._gql_enums['directionEnum'] = GraphQLEnumType( 'directionEnum', values=OrderedDict(ASC=GraphQLEnumValue(), DESC=GraphQLEnumValue()), description='Enum value used to specify ordering direction.', ) self._gql_enums['nullsOrderingEnum'] = GraphQLEnumType( 'nullsOrderingEnum', values=OrderedDict( SMALLEST=GraphQLEnumValue(), BIGGEST=GraphQLEnumValue(), ), description='Enum value used to specify how nulls are ordered.', ) scalar_types = list( self.edb_schema.get_objects(included_modules=self.modules, type=s_scalars.ScalarType)) for st in scalar_types: if st.is_enum(self.edb_schema): t_name = st.get_name(self.edb_schema) gql_name = self.get_gql_name(t_name) enum_type = GraphQLEnumType( gql_name, values=OrderedDict( (key, GraphQLEnumValue()) for key in st.get_enum_values(self.edb_schema)), description=self._get_description(st), ) self._gql_enums[gql_name] = enum_type self._gql_inobjtypes[f'Insert{t_name}'] = enum_type
def get_update_column_enums(model: DeclarativeMeta) -> GraphQLEnumType: type_name = get_model_column_update_enum_name(model) fields = {} for column in get_table(model).columns: fields[column.name] = column.name return GraphQLEnumType(type_name, fields)
def create_type(): return GraphQLEnumType( name='MedicareUtilizationLevel', values={ 'NONE': GraphQLEnumValue(), 'LOW': GraphQLEnumValue(), 'FULL': GraphQLEnumValue(), }, )
def get_constraint_enum(model: DeclarativeMeta) -> GraphQLEnumType: type_name = get_field_name(model, "constraint") fields = {} for column in get_table(model).primary_key: key_name = get_field_name(model, "pkey") fields[key_name] = key_name return GraphQLEnumType(type_name, fields)
def get_constraint_enum(model: DeclarativeMeta) -> GraphQLEnumType: type_name = get_model_constraint_enum_name(model) fields = {} for column in get_table(model).primary_key: key_name = get_model_constraint_key_name(model, column, is_primary_key=True) fields[key_name] = key_name return GraphQLEnumType(type_name, fields)
def create_type(): return GraphQLEnumType( name='ProviderStatus', values={ 'AS_SUBMITTED': GraphQLEnumValue(), 'SETTLED': GraphQLEnumValue(), 'AMENDED': GraphQLEnumValue(), 'SETTLED_WITH_AUDIT': GraphQLEnumValue(), 'REOPENED': GraphQLEnumValue(), }, )
def get_enum_type(enum_definition: EnumDefinition, type_map: TypeMap) -> GraphQLEnumType: if enum_definition.name not in type_map: enum = GraphQLEnumType( name=enum_definition.name, values={ item.name: GraphQLEnumValue(item.value) for item in enum_definition.values }, description=enum_definition.description, ) type_map[enum_definition.name] = ConcreteType( definition=enum_definition, implementation=enum) return cast(GraphQLEnumType, type_map[enum_definition.name].implementation)
def _process_enum(cls, name=None, description=None): if not isinstance(cls, EnumMeta): raise NotAnEnum() if not name: name = cls.__name__ description = description or cls.__doc__ graphql_type = GraphQLEnumType( name=name, values=[(item.name, GraphQLEnumValue(item.value)) for item in cls], description=description, ) register_type(cls, graphql_type) return cls
def _process_enum(cls, name=None, description=None): if not isinstance(cls, EnumMeta): raise NotAnEnum() if not name: name = cls.__name__ REGISTRY[name] = cls description = description or cls.__doc__ cls.field = GraphQLEnumType( name=name, values=[(item.name, GraphQLEnumValue(item.value)) for item in cls], description=description, ) return cls
def from_enum(self, enum: EnumDefinition) -> GraphQLEnumType: assert enum.name is not None # Don't reevaluate known types if enum.name in self.type_map: graphql_enum = self.type_map[enum.name].implementation assert isinstance(graphql_enum, GraphQLEnumType) # For mypy return graphql_enum graphql_enum = GraphQLEnumType( name=enum.name, values={ item.name: self.from_enum_value(item) for item in enum.values }, description=enum.description, ) self.type_map[enum.name] = ConcreteType(definition=enum, implementation=graphql_enum) return graphql_enum
def __init__(self, session): self.type_map = { "Test": GraphQLObjectType("Test", GraphQLField(GraphQLList(GraphQLString))), "TestEmptyObject": GraphQLObjectType("TestEmptyObject", {}), "TestNestedObjects": GraphQLObjectType( "TestNestedObjects", { "EnumField": GraphQLField( GraphQLEnumType("TestEnum", { "RED": 0, "GREEN": 1, "BLUE": 2 })), "InputField": GraphQLInputField(GraphQLNonNull(GraphQLInt)), "List": GraphQLList(GraphQLString), "InputObjectType": GraphQLInputObjectType( "TestInputObject", GraphQLNonNull( GraphQLUnionType("TestUnion", [GraphQLString, GraphQLID])), ), "ArgumentType": GraphQLArgument(GraphQLBoolean), "Float": GraphQLFloat, }, ), } self.context = session
def test_enum_select(self): """ Update SDL.User.desk_theme return type to be an Enum """ from graphql import GraphQLScalarType, GraphQLEnumType schema = get_schema() user_type = schema.type_map.get("User") original_type = None if isinstance( user_type.fields.get("desk_theme").type, GraphQLScalarType): original_type = user_type.fields.get("desk_theme").type user_type.fields.get("desk_theme").type = GraphQLEnumType( name="UserDeskThemeType", values={ "DARK": "DARK", "LIGHT": "LIGHT" }) r = execute(query=""" query FetchAdmin($user: String!) { User(name: $user) { full_name desk_theme } } """, variables={"user": "******"}) self.assertIsNone(r.get("errors")) admin = r.get("data").get("User") self.assertIn(admin.get("desk_theme"), ["LIGHT", "DARK"]) # Set back the original type if original_type is not None: user_type.fields.get("desk_theme").type = original_type
def get_droid(id): return Droid(id='2001', name='R2-D2', friends=['1000', '1002', '1003'], appearsIn=[4, 5, 6], primaryFunction='Astromech') def get_secret_backstory(character): return None episode_enum = GraphQLEnumType( 'Episode', { 'NEWHOPE': GraphQLEnumValue(4, description='Released in 1977.'), 'EMPIRE': GraphQLEnumValue(5, description='Released in 1980.'), 'JEDI': GraphQLEnumValue(6, description='Released in 1983.') }, description='One of the films in the Star Wars Trilogy') character_interface = GraphQLInterfaceType( 'Character', lambda: { 'id': GraphQLField(GraphQLNonNull(GraphQLString), description='The id of the character.'), 'name': GraphQLField(GraphQLString, description='The name of the character.'), 'friends': GraphQLField(GraphQLList(character_interface), description='The friends of the character,'
def test_simple_query_with_enums_default_value(module_compiler): """ enum LengthUnit { METER KM } type Starship { id: ID! name: String! length(unit: LengthUnit = METER): Float } type Query { ship(id: String!): Starship } """ length_unit_enum = GraphQLEnumType( 'LengthUnit', { 'METER': GraphQLEnumValue('METER'), 'KM': GraphQLEnumValue('KM'), }, description='One of the films in the Star Wars Trilogy', ) starship_type = GraphQLObjectType( 'Starship', lambda: { 'id': GraphQLField(GraphQLNonNull(GraphQLString), description='The id of the ship.'), 'name': GraphQLField(GraphQLString, description='The name of the ship.'), 'length': GraphQLField(GraphQLInt, args={ 'unit': GraphQLArgument(GraphQLNonNull(length_unit_enum), default_value='METER', description='id of the droid') }) }) query_type = GraphQLObjectType( 'Query', lambda: { 'ship': GraphQLField( starship_type, args={ 'id': GraphQLArgument(GraphQLNonNull(GraphQLString), description='id of the ship') }, ) }) schema = GraphQLSchema(query_type, types=[length_unit_enum, starship_type]) query = """ query GetStarship { ship(id: "Enterprise") { id name length(unit: METER) } } """ query_parser = QueryParser(schema) query_renderer = DataclassesRenderer( schema, Config(schema='schemaurl', endpoint='schemaurl', documents='')) parsed = query_parser.parse(query) rendered = query_renderer.render(parsed) m = module_compiler(rendered) response = m.GetStarship.from_json(""" { "data": { "ship": { "id": "Enterprise", "name": "Enterprise", "length": 100 } } } """) assert response ship = response.data.ship assert ship assert ship.id == 'Enterprise' assert ship.name == 'Enterprise' assert ship.length == 100
GraphQLObjectType, GraphQLString, GraphQLField, GraphQLNonNull, GraphQLID, GraphQLEnumType, GraphQLEnumValue, GraphQLList ) from ...utils.resolver import resolve_with_loader ContestStatusType = GraphQLEnumType( name='ContestStatusType', values=OrderedDict([ ('draft', GraphQLEnumValue('draft')), ('published', GraphQLEnumValue('published')), ('archived', GraphQLEnumValue('archived')), ]) ) ContestType = GraphQLObjectType( name='ContestType', fields=lambda: { 'id': GraphQLField(GraphQLID), 'code': GraphQLField(GraphQLNonNull(GraphQLString)), 'title': GraphQLField(GraphQLNonNull(GraphQLString)), 'description': GraphQLField(GraphQLString), 'status': GraphQLField(GraphQLNonNull(ContestStatusType)), 'createdAt': GraphQLField(GraphQLNonNull(GraphQLString)), 'names': GraphQLField( GraphQLList(NameType),
def convert(self, type_map: t.Dict[str, GraphQLType]) -> GraphQLEnumType: if self.name in type_map: return t.cast(GraphQLEnumType, type_map[self.name]) type_map[self.name] = GraphQLEnumType(self.name, self.values) return t.cast(GraphQLEnumType, type_map[self.name])
BLUE = 2 YELLOW = 3 CYAN = 4 MAGENTA = 5 RED = Color.RED GREEN = Color.GREEN BLUE = Color.BLUE YELLOW = Color.YELLOW CYAN = Color.CYAN MAGENTA = Color.MAGENTA ALL_COLORS = [c for c in Color] ColorType = GraphQLEnumType("Color", {c.name: c for c in Color}) def resolve_opposite(_root, _info, color): opposite_colors = { RED: CYAN, GREEN: MAGENTA, BLUE: YELLOW, YELLOW: BLUE, CYAN: RED, MAGENTA: GREEN, } return opposite_colors[color]
def get_droid(root, _info, id): """Allows us to query for the droid with the given id.""" return droid_data.get(id) def get_secret_backstory(_character, _info): """Raise an error when attempting to get the secret backstory.""" raise RuntimeError("secretBackstory is secret.") episode_enum = GraphQLEnumType( "Episode", { "NEWHOPE": GraphQLEnumValue(4, description="Released in 1977."), "EMPIRE": GraphQLEnumValue(5, description="Released in 1980."), "JEDI": GraphQLEnumValue(6, description="Released in 1983."), }, description="One of the films in the Star Wars Trilogy", ) character_interface = GraphQLInterfaceType( "Character", lambda: { "id": GraphQLField( GraphQLNonNull(GraphQLString), description="The id of the character." ), "name": GraphQLField(GraphQLString, description="The name of the character."), "friends": GraphQLField( GraphQLList(character_interface),
def transform_serializer_field(path, name, schema, model_schema, use_list=False): # TODO: self ref if schema.get("$ref", None): type_name = schema["$ref"].replace("#/definitions/", "") definitions = model_schema.get("definitions", {}) return transform_serializer_field( f"{path}", name, definitions[type_name], model_schema, ) required = True schema_type = schema.get("type", None) if schema_type == "object": properties = schema.get("properties", {}) fields = {} for field_name, field_schema in properties.items(): fields[field_name] = transform_serializer_field( f"{path}/{field_name}", field_name, field_schema, model_schema, ) return ObjectType( name, fields=fields, ) print("path->", path) if schema.get("enum", None): return GraphQLField( GraphQLEnumType( f"{name}_{randint(1, 200)}", values=dict(zip(schema["enum"], schema["enum"])), )) if schema_type == "string": if schema.get("format", None) == "date": return create_scalar_field(name, rs.Date, required, use_list=use_list) if schema.get("format", None) == "date-time": return create_scalar_field(name, rs.DateTime, required, use_list=use_list) return create_scalar_field(name, rs.String, required, use_list=use_list) if schema_type == "integer": return create_scalar_field(name, rs.Int, required, use_list=use_list) if schema_type == "array": return transform_serializer_field(f"{path}", name, schema["items"], model_schema, use_list=True) raise NotImplementedError
self.emit_event(MutationEnum.DELETED, user) return user def emit_event(self, mutation: MutationEnum, user: User) -> None: """Emit mutation events for the given object and its class""" emit = self._emitter.emit payload = {"user": user, "mutation": mutation.value} emit("User", payload) # notify all user subscriptions emit(f"User_{user.id}", payload) # notify single user subscriptions def event_iterator(self, id_: str) -> EventEmitterAsyncIterator: event_name = "User" if id_ is None else f"User_{id_}" return EventEmitterAsyncIterator(self._emitter, event_name) mutation_type = GraphQLEnumType("MutationType", MutationEnum) user_type = GraphQLObjectType( "UserType", { "id": GraphQLField(GraphQLNonNull(GraphQLID)), "firstName": GraphQLField(GraphQLNonNull(GraphQLString)), "lastName": GraphQLField(GraphQLNonNull(GraphQLString)), "tweets": GraphQLField(GraphQLInt), "verified": GraphQLField(GraphQLNonNull(GraphQLBoolean)), }, ) user_input_type = GraphQLInputObjectType( "UserInputType", {
def test_simple_query_with_enums_default_value(self): """ enum LengthUnit { METER KM } type Starship { id: ID! name: String! length(unit: LengthUnit = METER): Float } type Query { ship(id: String!): Starship } """ length_unit_enum = GraphQLEnumType( "LengthUnit", { "METER": GraphQLEnumValue("METER"), "KM": GraphQLEnumValue("KM") }, description="One of the films in the Star Wars Trilogy", ) starship_type = GraphQLObjectType( "Starship", lambda: { "id": GraphQLField(GraphQLNonNull(GraphQLString), description="The id of the ship."), "name": GraphQLField(GraphQLString, description="The name of the ship."), "length": GraphQLField( GraphQLInt, args={ "unit": GraphQLArgument( GraphQLNonNull(length_unit_enum), default_value="METER", description="id of the droid", ) }, ), }, ) query_type = GraphQLObjectType( "Query", lambda: { "ship": GraphQLField( starship_type, args={ "id": GraphQLArgument(GraphQLNonNull(GraphQLString), description="id of the ship") }, ) }, ) schema = GraphQLSchema(query_type, types=[length_unit_enum, starship_type]) query = """ query GetStarship { ship(id: "Enterprise") { id name length(unit: METER) } } """ query_parser = QueryParser(schema) query_renderer = DataclassesRenderer(schema) parsed = query_parser.parse(query) rendered_enums = query_renderer.render_enums(parsed) for rendered_enum in rendered_enums: self.load_module(rendered_enum) rendered = query_renderer.render(parsed) m = self.load_module(rendered) response = m.GetStarship.from_json(""" { "data": { "ship": { "id": "Enterprise", "name": "Enterprise", "length": 100 } } } """) assert response ship = response.data.ship assert ship assert ship.id == "Enterprise" assert ship.name == "Enterprise" assert ship.length == 100
"isCorrect": GraphQLField(GraphQLBoolean, description="If the CF is correct."), }, ) nameArg = GraphQLArgument( type=GraphQLNonNull(GraphQLString), description="Person's first name(s)" ) surnameArg = GraphQLArgument( type=GraphQLNonNull(GraphQLString), description="Person's last name(s)" ) genderType = GraphQLEnumType( "Gender", description="One's official gender.", values={ "M": GraphQLEnumValue("M", description="Male"), "F": GraphQLEnumValue("F", description="Female"), }, ) genderArg = GraphQLArgument( type=GraphQLNonNull(genderType), description="Person's official gender" ) placeOfBirthArg = GraphQLArgument( type=GraphQLNonNull(GraphQLString), description="Person's place of birth" ) dateOfBirthArg = GraphQLArgument( type=GraphQLNonNull(GraphQLString), description="Person's date of birth" )
def graphql_type(cls): return GraphQLEnumType( name=getattr(cls.Meta, "name", cls.__name__), description=getattr(cls.Meta, "description", cls.__doc__), values=getattr(cls.Meta, "values", cls._values), )
def __init_subclass__(cls): super().__init_subclass__() model_meta = inspect(cls.Meta.model) for column in model_meta.columns.values(): cls._fields[column.name] = column_to_field(column) cls._fields[column.name].bind(cls) for relationship in model_meta.relationships: name = relationship.key cls._fields[name] = relationship_to_field(relationship) cls._fields[name].bind(cls) cls._types["SQLAOrder"] = GraphQLEnumType("SQLAOrder", SQLAOrder) cls._columns_enum = Enum( f"{cls.__name__}Columns", [(column.name, column.name) for column in model_meta.columns.values()], ) cls._columns = GraphQLEnumType(cls._columns_enum.__name__, cls._columns_enum) cls._types[cls._columns.name] = cls._columns cls._unique_columns_enum = Enum( f"{cls.__name__}UniqueColumns", [(column.name, column.name) for column in model_meta.columns.values() if column.unique or column.primary_key], ) cls._unique_columns = GraphQLEnumType( cls._unique_columns_enum.__name__, cls._unique_columns_enum) cls._types[cls._unique_columns.name] = cls._unique_columns cls._queries[cls.__name__.lower()] = Field( type_=cls.__name__, resolve=partial(resolve_single, cls), args={ "column": Argument(type_=cls._unique_columns.name), "value": Argument(type_=String), }, ) cls._queries[cls.__name__.lower()].bind(cls) cls._queries[f"{cls.__name__.lower()}s"] = Field( type_=cls.__name__, resolve=partial(resolve_many, cls), many=True, args={ "like_by": Argument(type_=cls._columns.name, many=True, required=False), "like": Argument(type_=String, many=True, required=False), "order_by": Argument(type_=cls._columns.name, many=True, required=False), "order": Argument(type_="SQLAOrder", many=True, required=False), "page": Argument(type_=Int, required=False), "limit": Argument(type_=Int, required=False), }, ) cls._queries[f"{cls.__name__.lower()}s"].bind(cls)
GraphQLInputObjectType, GraphQLList, GraphQLNonNull, GraphQLScalarType, GraphQLString, ) from sqlalchemy import Float, Integer from typing import Union, Dict, cast from .graphql_types import get_graphql_type_from_column from .helpers import get_relationships, get_table from .names import get_field_name from .types import Inputs from sqlalchemy.ext.declarative import DeclarativeMeta ORDER_BY_ENUM = GraphQLEnumType("order_by", {"desc": "desc", "asc": "asc"}) def get_empty_dict() -> Dict[str, GraphQLInputField]: return {} def get_type_comparison_fields(graphql_type: Union[GraphQLScalarType, GraphQLList], inputs: Inputs, type_name: str) -> GraphQLInputObjectType: if type_name in inputs: return inputs[type_name] fields = { "_eq": GraphQLInputField(graphql_type),
subscription=GraphQLObjectType( name="RootSubscriptionType", fields={ "runCmd": GraphQLField(GraphQLString, args={ 'id': GraphQLArgument(GraphQLNonNull(GraphQLInt)), 'cmd': GraphQLArgument( GraphQLEnumType( "Cmd", values={ 'up': GraphQLEnumValue('up'), 'down': GraphQLEnumValue('down'), 'pause': GraphQLEnumValue('pause'), 'unpause': GraphQLEnumValue('unpause'), 'logs': GraphQLEnumValue('logs'), 'destroy': GraphQLEnumValue('destroy') })) }, resolve=lambda x, i, id, cmd: x, subscribe=subscribe_run_cmd), "execServiceCmd": GraphQLField(GraphQLString, args={ 'stack_id': GraphQLArgument(GraphQLNonNull(GraphQLInt)), 'service_name': GraphQLArgument(GraphQLNonNull(GraphQLString)),