union SearchResult = User | Post | Comment
typeQuery{
search(query: String!):[SearchResult!]!}# Query example{
search(query:"graphql"){...on User {
name
email
}...on Post {
title
content
}...on Comment {
text
author {
name
}}}}
type User {firstName: String!lastName: String!fullName: String!# Computed in resolverposts:[Post!]!postCount: Int!# Computed, doesn't load all posts}type Post {likeCount: Int!commentCount: Int!isLikedByViewer: Boolean!# Context-dependent}
Subscriptions
typeSubscription{postAdded: Post!
postUpdated(postId: ID!): Post!
userStatusChanged(userId: ID!): UserStatus!}type UserStatus {userId: ID!online: Boolean!lastSeen: DateTime!}# Client usagesubscription{
postAdded {
id
title
author {
name
}}}
type User {name: String!email: String!@deprecated(reason:"Use emails field instead")emails:[String!]!# Conditional inclusionprivateData: PrivateData @include(if:$isOwner)
}# Queryquery GetUser($isOwner: Boolean!){
user(id:"123"){
name
privateData @include(if:$isOwner) {
ssn
}}}
Custom Directives
directive@auth(requires: Role = USER)on FIELD_DEFINITION
enum Role {
USER
ADMIN
MODERATOR
}typeMutation{
deleteUser(id: ID!): Boolean!@auth(requires: ADMIN)
updateProfile(input: ProfileInput!): User!@auth}
Error Handling
Union Error Pattern
type User {id: ID!email: String!}type ValidationError {field: String!message: String!}type NotFoundError {message: String!resourceType: String!resourceId: ID!}type AuthorizationError {message: String!}union UserResult = User | ValidationError | NotFoundError | AuthorizationError
typeQuery{
user(id: ID!): UserResult!}# Usage{
user(id:"123"){...on User {
id
email
}...on NotFoundError {
message
resourceType
}...on AuthorizationError {
message
}}}
Errors in Payload
type CreateUserPayload {user: User
errors:[Error!]success: Boolean!}type Error {field: String
message: String!code: ErrorCode!}enum ErrorCode {
VALIDATION_ERROR
UNAUTHORIZED
NOT_FOUND
INTERNAL_ERROR
}
N+1 Query Problem Solutions
DataLoader Pattern
from aiodataloader import DataLoader
classPostLoader(DataLoader):
asyncdefbatch_load_fn(self, post_ids):
posts = await db.posts.find({"id": {"$in": post_ids}})
post_map = {post["id"]: post for post in posts}
return [post_map.get(pid) for pid in post_ids]
# Resolver@user_type.field("posts")asyncdefresolve_posts(user, info):
loader = info.context["loaders"]["post"]
returnawait loader.load_many(user["post_ids"])
Query Depth Limiting
from graphql import GraphQLError
defdepth_limit_validator(max_depth: int):
defvalidate(context, node, ancestors):
depth = len(ancestors)
if depth > max_depth:
raise GraphQLError(
f"Query depth {depth} exceeds maximum {max_depth}"
)
return validate