@__xuorig__
module Api
class GraphqlController < ApiController
def query
query_string = params[:query]
variables = params[:variables]
context = {
current_user: current_user
}
# ...
end
end
end
Slide 73
Slide 73 text
@__xuorig__
module Api
class GraphqlController < ApiController
def query
# ...
result = MySchema.query(
query_string,
variables: variables,
context: context
)
render json: result
end
end
end
Slide 74
Slide 74 text
@__xuorig__
Drawbacks
and solutions
Slide 75
Slide 75 text
@__xuorig__
N+1 Queries
Slide 76
Slide 76 text
@__xuorig__
# Product Type
field :image do
type ImageType
resolve -> (product, args, ctx) do
product.image
end
end
# Shop Type
field :products do
type [ProductType]
resolve -> (shop, args, ctx) do
shop.products
end
end
Slide 77
Slide 77 text
@__xuorig__
Product Load (1.0ms) SELECT "products".* FROM "products"
WHERE "products"."shop_id" = …
Image Load (0.9ms) SELECT "images".* FROM "images"
WHERE "images"."product_id" = …
Image Load (0.2ms) SELECT "images".* FROM "images"
WHERE "images"."product_id" = …
Image Load (0.1ms) SELECT "images".* FROM "images"
WHERE "images"."product_id" = …
Slide 78
Slide 78 text
@__xuorig__
Solution: Batching + Caching
Slide 79
Slide 79 text
@__xuorig__
field :image do
type ImageType
resolve -> (product, args, ctx) do
RecordLoader.for(Image).load(product.image_id)
end
end
@__xuorig__
query {
shop {
name
description
products {
name
price
}
}
}
Slide 93
Slide 93 text
@__xuorig__
query {
shop {
name
description
products {
name
price
}
}
}
Slide 94
Slide 94 text
@__xuorig__
query {
shop {
name
description
products @defer {
name
price
}
}
}
Slide 95
Slide 95 text
@__xuorig__
Slide 96
Slide 96 text
@__xuorig__
yo, give me the resource with id = abc
OK, here’s the resource with id = abc
Client Server
Slide 97
Slide 97 text
@__xuorig__
Client Server
yo, give me the resource with id = 1
yo, give me the resource with id = 2
yo, give me the resource with id = 3
yo, give me the resource with id = 4
Slide 98
Slide 98 text
@__xuorig__
oh boy :(
Client Server
Slide 99
Slide 99 text
@__xuorig__
I need that exact data shape (requirements)
Here is everything you can do! (capabilities)
Client Server