class Deadline: type: str name: str = strawberry.field(resolver=make_localized_resolver("name")) description: str = strawberry.field(resolver=make_localized_resolver("description")) start: DateTime end: DateTime conference: Conference
class Post: id: strawberry.ID author: BlogPostAuthor title: str = strawberry.field(resolver=make_localized_resolver("title")) slug: str = strawberry.field(resolver=make_localized_resolver("slug")) excerpt: str = strawberry.field( resolver=make_localized_resolver("excerpt")) content: str = strawberry.field( resolver=make_localized_resolver("content")) image: Optional[str] published: datetime def __init__( self, id: strawberry.ID, author: BlogPostAuthor, title: str, slug: str, excerpt: str, content: str, published: datetime, image: Optional[str], ) -> None: self.id = id self.author = author self.title = title self.slug = slug self.excerpt = excerpt self.content = content self.published = published self.image = image
class RulesQuery: name_re: Optional[str] = strawberry.field( default=None, description="Select rules matching a regexp." ) limit: Optional[int] = strawberry.field( default=None, description="Limit the number of entries returned." ) def __bool__(self) -> bool: return not (self.name_re is None and self.limit is None) @staticmethod def filter(query: RulesQuery | None, rules: Iterable[RuleInfo]) -> Iterator[RuleInfo]: if not query: yield from rules return name_pattern = query.name_re and re.compile(query.name_re) count = 0 for info in rules: if name_pattern and not re.match(name_pattern, info.name): continue yield info count += 1 if query.limit and count >= query.limit: return
class Query: hello: str = strawberry.field(resolver=function_resolver) hello_async: str = strawberry.field(resolver=async_resolver) get_name: str = strawberry.field(resolver=resolve_name) say_hello: str = strawberry.field(resolver=resolve_say_hello) name = "Patrick"
class TargetsQuery: specs: Optional[List[str]] = strawberry.field( default=None, description= ("Select targets matching the address specs. (Same syntax as supported on the command line.)" ), ) target_type: Optional[str] = strawberry.field( default=None, description="Select targets of a certain type only.") limit: Optional[int] = strawberry.field( default=None, description="Limit the number of entries returned.") def __bool__(self) -> bool: # The `specs` field is not used in the `filter` method. return not (self.target_type is None and self.limit is None) @staticmethod def filter(query: TargetsQuery | None, targets: Iterable[TargetData]) -> Iterator[TargetData]: if not query: yield from targets return count = 0 for data in targets: if query.target_type and data.target.alias != query.target_type: continue yield data count += 1 if query.limit and count >= query.limit: return
class TargetTypesQuery: alias_re: Optional[str] = strawberry.field( default=None, description="Select targets types matching a regexp.") limit: Optional[int] = strawberry.field( default=None, description="Limit the number of entries returned.") def __bool__(self) -> bool: return not (self.alias_re is None and self.limit is None) @staticmethod def filter(query: TargetTypesQuery | None, target_types: Iterable[TargetType]) -> Iterator[TargetType]: if not query: yield from target_types return alias_pattern = query.alias_re and re.compile(query.alias_re) count = 0 for info in target_types: if alias_pattern and not re.match(alias_pattern, info.alias): continue yield info count += 1 if query.limit and count >= query.limit: return
class HotelRoom: id: str name: str = strawberry.field(resolver=make_localized_resolver("name")) description: str = strawberry.field( resolver=make_localized_resolver("description")) price: str is_sold_out: bool capacity_left: int
class Page: id: strawberry.ID title: str = strawberry.field(resolver=make_localized_resolver("title")) slug: str = strawberry.field(resolver=make_localized_resolver("slug")) content: str = strawberry.field( resolver=make_localized_resolver("content")) excerpt: Optional[str] image: Optional[str] = strawberry.field(resolver=resolve_image)
class Deadline: id: strawberry.ID type: str name: str = strawberry.field(resolver=make_localized_resolver("name")) description: str = strawberry.field(resolver=make_localized_resolver("description")) start: datetime end: datetime conference: Conference status: DeadlineStatusType
class Query: hello: str = strawberry.field(resolver=function_resolver) hello_with_root: str = strawberry.field( resolver=function_resolver_with_root) hello_with_params: str = strawberry.field( resolver=function_resolver_with_params) def __post_init__(self): self._example = "Example"
class Query: person: Person = strawberry.field( resolver=resolve_person, description="this is always returning same person") person_by_id: typing.Optional[Person] = strawberry.field( resolver=resolve_person_by_id, description="get from people db") @strawberry.field def company(self, info) -> Company: return Company(name="BAC", space="BCA")
class Event: id: strawberry.ID conference: LazyType["Conference", "api.conferences.types"] title: str = strawberry.field(resolver=make_localized_resolver("title")) slug: str = strawberry.field(resolver=make_localized_resolver("slug")) content: str = strawberry.field( resolver=make_localized_resolver("content")) map: Optional[Map] = strawberry.field(resolver=resolve_map) image: Optional[str] = strawberry.field(resolver=resolve_image) location_name: Optional[str] start: datetime end: datetime
class Event: id: strawberry.ID conference: "Conference" title: str = strawberry.field(resolver=make_localized_resolver("title")) slug: str = strawberry.field(resolver=make_localized_resolver("slug")) content: str = strawberry.field( resolver=make_localized_resolver("content")) map: Optional[Map] = strawberry.field(resolver=resolve_map) image: Optional[str] = strawberry.field(resolver=resolve_image) location_name: Optional[str] start: DateTime end: DateTime
class ActionInput: value: JSON = strawberry.field( description='Action definition, "delete" for action deletion' ) # except with deletion always required as actions must be checked and # transformed by server existingHash: Optional[str] = None start: Optional[datetime] = None stop: Optional[datetime] = None key: Optional[str] = strawberry.field( description="Action key for encrypting action (base64, 32 bytes)", default=None, )
def wrap(cls): if not fields: raise MissingFieldsListError(model) model_fields = model.__fields__ fields_set = set(fields) all_fields = [( name, get_type_for_field(field), dataclasses.field(default=strawberry.field( name=to_camel_case(field.alias))), ) for name, field in model_fields.items() if name in fields_set] cls_annotations = getattr(cls, "__annotations__", {}) all_fields.extend((( name, type_, dataclasses.field(default=strawberry.field( name=to_camel_case(name))), ) for name, type_ in cls_annotations.items())) cls = dataclasses.make_dataclass( cls.__name__, all_fields, ) _process_type( cls, name=name, is_input=is_input, is_interface=is_interface, description=description, federation=federation, ) model._strawberry_type = cls # type: ignore def from_pydantic(instance: Any, extra: Dict[str, Any] = None) -> Any: return convert_pydantic_model_to_strawberry_class( cls=cls, model_instance=instance, extra=extra) def to_pydantic(self) -> Any: instance_kwargs = dataclasses.asdict(self) return model(**instance_kwargs) cls.from_pydantic = staticmethod(from_pydantic) cls.to_pydantic = to_pydantic return cls
class KeynoteSpeaker: id: ID name: str bio: str = strawberry.field(resolver=make_localized_resolver("bio")) pronouns: str = strawberry.field(resolver=make_localized_resolver("pronouns")) twitter_handle: str instagram_handle: str website: str highlight_color: str _photo_url: Private[str] def __init__( self, id: ID, name: str, bio: str, pronouns: str, twitter_handle: str, instagram_handle: str, website: str, highlight_color: str, _photo_url: str, ): self.id = id self.name = name self.bio = bio self.pronouns = pronouns self.twitter_handle = twitter_handle self.instagram_handle = instagram_handle self.website = website self.highlight_color = highlight_color self._photo_url = _photo_url @strawberry.field def photo(self, info) -> str: return info.context.request.build_absolute_uri(self._photo_url) @classmethod def from_django_model(cls, instance): return cls( id=instance.id, name=instance.name, _photo_url=instance.photo.url, bio=instance.bio, pronouns=instance.pronouns, highlight_color=instance.highlight_color, twitter_handle=instance.twitter_handle, instagram_handle=instance.instagram_handle, website=instance.website, )
class Query: library: Library = field(resolver=resolve_library) hello: str = field(resolver=resolve_hello) hello_async: str = field(resolver=resolve_hello_async) search: List[Item] = field(resolver=resolve_search) echo: str = field(resolver=resolve_echo) storage: Storage = field(resolver=resolve_storage) error: Optional[str] = field(resolver=resolve_error) error_non_null: str = field(resolver=resolve_error) def resolve_library(self, info, index): return libraries[index] def resolve_storage(self, info): return storage def resolve_search(self, info, contains): search_books = [b for b in books if contains in b.name] search_magazines = [m for m in magazines if contains in m.name] return search_books + search_magazines def resolve_hello(self, info): return "Hello!" def resolve_echo(self, info, echo): return echo def resolve_error(self, info) -> str: raise RuntimeError("Runtime Error!")
class Post: id: strawberry.ID author: User title: str = strawberry.field(resolver=make_localized_resolver("title")) slug: str = strawberry.field(resolver=make_localized_resolver("slug")) excerpt: str = strawberry.field(resolver=make_localized_resolver("excerpt")) content: str = strawberry.field(resolver=make_localized_resolver("content")) published: DateTime @strawberry.field def image(self, info) -> Optional[str]: if not self.image: return None return info.context["request"].build_absolute_uri(self.image.url)
class ReferenceInput: target: ID = strawberry.field( description="Can be node id, direct id of content or hash of key", ) extra: Optional[str] = None group: Optional[str] = None deleteRecursive: Optional[DeleteRecursive] = None
class User: password: strawberry.auto new_age: int = strawberry.field(resolver=some_resolver) @strawberry.field def age() -> int: return 42
class Target: address: str = strawberry.field(description="The target address.") target_type: str = strawberry.field( description= "The target type, such as `python_sources` or `pex_binary` etc.") fields: JSONScalar = strawberry.field(description=softwrap(""" The targets field values. This has the same structure as the JSON output from the `peek` goal, i.e. some fields may be both on a `_raw` form as well as on a parsed/populated form. """)) @classmethod def from_data(cls, data: TargetData) -> Target: json = data.to_dict() address = json.pop("address") target_type = json.pop("target_type") fields = json return cls(address=address, target_type=target_type, fields=fields)
class Film(Node): title: typing.Optional[str] = strawberry.field( description="The title of this film." ) episode_id: typing.Optional[int] = strawberry.field( name="episodeID", description="The episode number of this film." ) opening_crawl: typing.Optional[str] = strawberry.field( description="The opening paragraphs at the beginning of this film." ) director: typing.Optional[str] = strawberry.field( description="The name of the director of this film." ) producers: typing.List[typing.Optional[str]] = strawberry.field( description="The name(s) of the producer(s) of this film." ) release_date: typing.Optional[str] = strawberry.field( description=( "The ISO 8601 date format of film " "release at original creator country." ) ) created: typing.Optional[str] = strawberry.field( description=( "The ISO 8601 date format of the time that " "this resource was created." ) ) edited: typing.Optional[str] = strawberry.field( description=( "The ISO 8601 date format of the time that " "this resource was edited." ) ) @strawberry.field async def species_connection( self, info, after: typing.Optional[str] = None, first: typing.Optional[int] = None, before: typing.Optional[str] = None, last: typing.Optional[int] = None, ) -> typing.Optional["FilmSpeciesConnection"]: # TODO: filtering return await get_connection_object( species, FilmSpeciesConnection, SpeciesEdge, after=after, first=first, before=before, last=last, )
def private_field() -> StrawberryField: """Field that can only be seen by admin and the submitter""" def resolver(self, info: Info): if CanSeeSubmissionPrivateFields().has_permission(self, info): return getattr(self, info.python_name) return None return strawberry.field(resolver=resolver)
def generate_model_type(resolver_cls, is_input=False, is_update=False): model = resolver_cls.model annotations = {} attributes = {'__annotations__': annotations} # add fields for field in model._meta.get_fields(): if resolver_cls.fields and field.name not in resolver_cls.fields: continue # skip if is_in(field.name, resolver_cls.exclude): continue # skip if is_input and is_in(field.name, resolver_cls.readonly_fields): continue # skip if field.is_relation: if isinstance(field, fields.related.ForeignKey): field_params = get_relation_foreignkey_field( field, is_input, is_update) else: if is_input: continue field_params = get_relation_field(field) else: field_params = get_field(field, is_input, is_update) if not field_params: continue field_name, field_type, field_kwargs = field_params if is_input: attributes[field_name] = strawberry.arguments.UNSET else: if resolver_cls.field_permission_classes: field_kwargs[ 'permission_classes'] = resolver_cls.field_permission_classes attributes[field_name] = strawberry.field(**field_kwargs) if field_type: annotations[field_name] = field_type if not is_input: for field_name in dir(resolver_cls): field = getattr(resolver_cls, field_name) if hasattr(field, '_field_definition'): attributes[field_name] = field # generate type type_name = model._meta.object_name if is_update: type_name = f'Update{type_name}' elif is_input: type_name = f'Create{type_name}' model_type = type(type_name, (), attributes) model_type = strawberry.type(model_type, is_input=is_input) if not is_input: register_model_type(model, model_type) register_resolver_cls(model, resolver_cls) return model_type
class Query: a: str = strawberry.field(description="Example") @strawberry.field def b(self, info, id: int) -> str: return "I'm a resolver" @strawberry.field(description="Example C") def c(self, info, id: int) -> str: return "I'm a resolver"
class Query: cone: IceCream = strawberry.field(resolver=makeIceCream) @strawberry.field def another_cone(self) -> IceCream: return IceCream(num_scoops=3, sequence_scoops=[ Flavour.STRAWBERRY, Flavour.CHOCOLATE, Flavour.VANILLA ])
def restricted_field() -> StrawberryField: """Field that can only be seen by admin, the submitter or who has the ticket until voting is not closed, after it will be public""" def resolver(self, info: Info): if CanSeeSubmissionRestrictedFields().has_permission(self, info): return getattr(self, info.python_name) return None return strawberry.field(resolver=resolver)
class Query: a: str = strawberry.field(deprecation_reason="Deprecated A") @strawberry.field def b(self, info, id: int) -> str: return "I'm a resolver" @strawberry.field(deprecation_reason="Deprecated B") def c(self, info, id: int) -> str: return "I'm a resolver"
class AppPost: id: int author_id: strawberry.ID author: Person title: str content: str comments: Collection[AppComment] = strawberry.field( description="Return all comments which have been added to this post," " wrapped in a `Collection`.") created: datetime updated: datetime
class AppComment: id: int post_id: int content: str author_id: strawberry.ID author: Person reactions: Collection[AppReaction] = strawberry.field( description="Return all reactions which have been set on this comment," " wrapped in a `Collection`.") created: datetime updated: datetime