在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):ashkan18/graphlient开源软件地址(OpenSource Url):https://github.com/ashkan18/graphlient开源编程语言(OpenSource Language):Ruby 100.0%开源软件介绍(OpenSource Introduction):GraphlientA friendlier Ruby client for consuming GraphQL-based APIs. Built on top of your usual graphql-client, but with better defaults, more consistent error handling, and using the faraday HTTP client. InstallationAdd the following line to your Gemfile. gem 'graphlient' UsageCreate a new instance of client = Graphlient::Client.new('https://test-graphql.biz/graphql',
headers: {
'Authorization' => 'Bearer 123'
},
http_options: {
read_timeout: 20,
write_timeout: 30
}
)
The schema is available automatically via client.schema # GraphQL::Schema Make queries with With a String. response = client.query <<~GRAPHQL
query {
invoice(id: 10) {
id
total
line_items {
price
item_type
}
}
}
GRAPHQL With a block. response = client.query do
query do
invoice(id: 10) do
id
total
line_items do
price
item_type
end
end
end
end This will call the endpoint setup in the configuration with query {
invoice(id: 10) {
id
total
line_items {
price
item_type
}
}
} A successful response object always contains data which can be iterated upon. The following example returns the first line item's price. response.data.invoice.line_items.first.price You can also execute mutations the same way. response = client.query do
mutation do
createInvoice(input: { fee_in_cents: 12_345 }) do
id
fee_in_cents
end
end
end The successful response contains data in response.data.create_invoice.first.id Schema storing and loading on diskTo reduce requests to graphql API you can cache schema: client = Client.new(url, schema_path: 'config/your_graphql_schema.json')
client.schema.dump! # you only need to call this when graphql schema changes Error HandlingUnlike graphql-client, Graphlient will always raise an exception unless the query has succeeded.
All errors inherit from Executing Parameterized Queries and MutationsGraphlient can execute parameterized queries and mutations by providing variables as query parameters. The following query accepts an array of IDs. With a String. query = <<-GRAPHQL
query($ids: [Int]) {
invoices(ids: $ids) {
id
fee_in_cents
}
}
GRAPHQL
variables = { ids: [42] }
client.query(query, variables) With a block. client.query(ids: [42]) do
query(ids: [:int]) do
invoices(ids: :ids) do
id
fee_in_cents
end
end
end Graphlient supports following Scalar types for parameterized queries by default:
You can use any of the above types with For any other custom types, graphlient will simply use The following mutation accepts a custom type that requires client.query(input: { fee_in_cents: 12_345 }) do
mutation(input: :createInvoiceInput!) do
createInvoice(input: :input) do
id
fee_in_cents
end
end
end Parse and Execute Queries SeparatelyYou can # parse a query, returns a GraphQL::Client::OperationDefinition
query = client.parse do
query(ids: [:int]) do
invoices(ids: :ids) do
id
fee_in_cents
end
end
end
# execute a query, returns a GraphQL::Client::Response
client.execute query, ids: [42] Or pass in a string instead of a block: # parse a query, returns a GraphQL::Client::OperationDefinition
query = client.parse <<~GRAPHQL
query($some_id: Int) {
invoice(id: $some_id) {
id
feeInCents
}
}
GRAPHQL
# execute a query, returns a GraphQL::Client::Response
client.execute query, ids: [42] Dynamic vs. Static QueriesGraphlient uses graphql-client, which recommends building queries as static module members along with dynamic variables during execution. This can be accomplished with graphlient the same way. Create a new instance of module SWAPI
Client = Graphlient::Client.new('https://test-graphql.biz/graphql',
headers: {
'Authorization' => 'Bearer 123'
},
allow_dynamic_queries: false
)
end The schema is available automatically via SWAPI::Client.schema # GraphQL::Schema Define a query. module SWAPI
InvoiceQuery = Client.parse do
query(id: :int) do
invoice(id: :id) do
id
fee_in_cents
end
end
end
end Execute the query. response = SWAPI::Client.execute(SWAPI::InvoiceQuery, id: 42) Note that in the example above the client is created with Generate Queries with Graphlient::QueryYou can directly use query = Graphlient::Query.new do
query do
invoice(id: 10) do
line_items
end
end
end
query.to_s
# "\nquery {\n invoice(id: 10){\n line_items\n }\n }\n" Create API Client Classes with Graphlient::Extension::QueryYou can include include Graphlient::Extensions::Query
query = query do
invoice(id: 10) do
line_items
end
end
query.to_s
# "\nquery{\n invoice(id: 10){\n line_items\n }\n }\n" Swapping the HTTP StackYou can swap the default Faraday adapter for client = Graphlient::Client.new('https://test-graphql.biz/graphql',
http: Graphlient::Adapters::HTTP::HTTPAdapter
) Testing with Graphlient and RSpecUse Graphlient inside your RSpec tests in a Rails application or with require 'spec_helper'
describe App do
include Rack::Test::Methods
def app
# ...
end
let(:client) do
Graphlient::Client.new('http://test-graphql.biz/graphql') do |client|
client.http do |h|
h.connection do |c|
c.adapter Faraday::Adapter::Rack, app
end
end
end
end
context 'an invoice' do
let(:result) do
client.query do
query do
invoice(id: 10) do
id
end
end
end
end
it 'can be retrieved' do
expect(result.data.invoice.id).to eq 10
end
end
end Alternately you can describe App do
let(:url) { 'http://example.com/graphql' }
let(:client) { Graphlient::Client.new(url) }
before do
stub_request(:post, url).to_return(
status: 200,
body: DummySchema.execute(GraphQL::Introspection::INTROSPECTION_QUERY).to_json
)
end
it 'retrieves schema' do
expect(client.schema).to be_a Graphlient::Schema
end
end In order to stub the response to actual queries, dump the schema into a JSON file and specify it via schema_path as follows. describe App do
let(:url) { 'http://graph.biz/graphql' }
let(:client) { Graphlient::Client.new(url, schema_path: 'spec/support/fixtures/invoice_api.json') }
let(:query) do
<<~GRAPHQL
query{
invoice(id: 42) {
id
feeInCents
}
}
GRAPHQL
end
let(:json_response) do
{
'data' => {
'invoice' => {
'id' => '42',
'feeInCents' => 2000
}
}
}.to_json
end
before do
stub_request(:post, url).to_return(
status: 200,
body: json_response
)
end
it 'returns invoice fees' do
response = client.query(query)
expect(response.data).to be_truthy
expect(response.data.invoice.id).to eq('42')
expect(response.data.invoice.fee_in_cents).to eq(2000)
end
end LicenseMIT License, see LICENSE |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论