import strawberryfrom typing import List, Optional@strawberry.typeclass Article: id: int title: str content: str@strawberry.typeclass User: id: int name: str avatar: str email: str articles: List[Article]# 模拟数据源mock_users = [ User(id=1, name="Alan", avatar="/img/1.png", email="zhang@example.com", articles=[Article(id=101, title="GraphQL入门", content="...")]), User(id=2, name="obalan", avatar="/img/2.png", email="li@example.com", articles=[]),]@strawberry.typeclass Query: @strawberry.field def user(self, id: int) -> Optional[User]: return next((u for u in mock_users if u.id == id), None)schema = strawberry.Schema(query=Query)
query {
user(id: 1) {
name
avatar
articles {
title
}
}
}{
"data": {
"user": {
"name": "ALan",
"avatar": "/img/1.png",
"articles": [
{ "title": "GraphQL入门" }
]
}
}}import strawberryfrom datetime import datetime@strawberry.typeclass Order: id: int amount: float create_time: datetime status: str@strawberry.typeclass Query: @strawberry.field def order_list(self, status: Optional[str] = None) -> List[Order]: """根据状态筛选订单列表""" # 业务逻辑... return [] @strawberry.field def order_detail(self, id: int) -> Optional[Order]: """获取订单详情""" # 业务逻辑... return None
import strawberryfrom typing import Listfrom strawberry.subscriptions import async_generator# Mutation 示例@strawberry.typeclass Mutation: @strawberry.mutation def create_user(self, name: str, email: str) -> User: new_user = User(id=3, name=name, avatar="", email=email, articles=[]) mock_users.append(new_user) return new_user# Subscription 示例(基于 WebSocket)@strawberry.typeclass Subscription: @strawberry.subscription async def count(self, target: int = 10) -> int: for i in range(target): yield i await asyncio.sleep(1)schema = strawberry.Schema(query=Query, mutation=Mutation, subscription=Subscription)
mutation {
createUser(name: "Alan", email: "1319242684@qq.com") {
id
name
}
}subscription {
count(target: 5)
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70050389/viewspace-3175808/ ,如需转载,请注明出处,否则将追究法律责任。