当前位置: 首页 > 软件库 > 大数据 > 数据查询 >

graphql-client

授权协议 View license
开发语言 Java
所属分类 大数据、 数据查询
软件类型 开源软件
地区 不详
投 递 者 焦光霁
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

graphql_client

Github actions Status

A typed GraphQL client library for Rust.

Features

  • Precise types for query variables and responses.
  • Supports GraphQL fragments, objects, unions, inputs, enums, custom scalars and input objects.
  • Works in the browser (WebAssembly).
  • Subscriptions support (serialization-deserialization only at the moment).
  • Copies documentation from the GraphQL schema to the generated Rust code.
  • Arbitrary derives on the generated responses.
  • Arbitrary custom scalars.
  • Supports multiple operations per query document.
  • Supports setting GraphQL fields as deprecated and having the Rust compiler checktheir use.
  • Optional reqwest-based client for boilerplate-free API calls from browsers.

Getting started

  • If you are not familiar with GraphQL, the official website provides a very good and comprehensive introduction.

  • Once you have written your query (most likely in something like graphiql), save it in a .graphql file in your project.

  • In order to provide precise types for a response, graphql_client needs to read the query and the schema at compile-time.

    To download the schema, you have multiple options. This projects provides a CLI, however it does not matter what tool you use, the resulting schema.json is the same.

  • We now have everything we need to derive Rust types for our query. This is achieved through a procedural macro, as in the following snippet:

    use graphql_client::GraphQLQuery;
    
    // The paths are relative to the directory where your `Cargo.toml` is located.
    // Both json and the GraphQL schema language are supported as sources for the schema
    #[derive(GraphQLQuery)]
    #[graphql(
        schema_path = "tests/unions/union_schema.graphql",
        query_path = "tests/unions/union_query.graphql",
    )]
    pub struct UnionQuery;

    The derive will generate a module named union_query in this example - the name is the struct's name, but in snake case.

    That module contains all the struct and enum definitions necessary to deserialize a response to that query.

    The root type for the response is named ResponseData. The GraphQL response will take the form of a Response<ResponseData> (the Response type is always the same).

    The module also contains a struct called Variables representing the variables expected by the query.

  • We now need to create the complete payload that we are going to send to the server. For convenience, the GraphQLQuery trait, is implemented for the struct under derive, so a complete query body can be created this way:

    use graphql_client::{GraphQLQuery, Response};
    use std::error::Error;
    use reqwest;
    
    #[derive(GraphQLQuery)]
    #[graphql(
        schema_path = "tests/unions/union_schema.graphql",
        query_path = "tests/unions/union_query.graphql",
        response_derives = "Debug",
    )]
    pub struct UnionQuery;
    
    async fn perform_my_query(variables: union_query::Variables) -> Result<(), Box<dyn Error>> {
    
        // this is the important line
        let request_body = UnionQuery::build_query(variables);
    
        let client = reqwest::Client::new();
        let mut res = client.post("/graphql").json(&request_body).send().await?;
        let response_body: Response<union_query::ResponseData> = res.json().await?;
        println!("{:#?}", response_body);
        Ok(())
    }

A complete example using the GitHub GraphQL API is available.

Alternative workflow using the CLI

You can introspect GraphQL APIs and generate module from a command line interface to the library:

$ cargo install graphql_client_cli
$ graphql-client --help

Deriving specific traits on the response

The generated response types always derive serde::Deserialize but you may want to print them (Debug), compare them (PartialEq) or derive any other trait on it. You can achieve this with the response_derives option of the graphql attribute. Example:

use graphql_client::GraphQLQuery;

#[derive(GraphQLQuery)]
#[graphql(
    schema_path = "tests/unions/union_schema.graphql",
    query_path = "tests/unions/union_query.graphql",
    response_derives = "Serialize,PartialEq",
)]
struct UnionQuery;

Custom scalars

In GraphQL, five scalar types, Int, Float, String, Boolean, and ID, are available out of the box and are automatically mapped to equivalent types in Rust. However, in addition, custom scalar types can be defined by service providers by adding declarations like scalar URI to the server schema.

If such custom scalar types are defined in the schema, depending on the content of the query, the generated code will also reference those scalar types. This means you have to provide matching Rust types in the scope of the struct under derive. It can be as simple as declarations like type URI = String;. This gives you complete freedom on how to treat custom scalars, as long as they can be deserialized. If such declarations are not provided, you will get build errors like this:

error[E0412]: cannot find type `URI` in module `super`
   |
   | #[derive(GraphQLQuery)]
   |          ^^^^^^^^^^^^ not found in `super`
   |
   = note: possible candidate is found in another module, you can import it into scope:
           crate::repo_view::URI

Deprecations

The generated code has support for @deprecatedfield annotations. You can configure how deprecations are handled via the deprecated argument in the GraphQLQuery derive:

use graphql_client::GraphQLQuery;

#[derive(GraphQLQuery)]
#[graphql(
  schema_path = "tests/unions/union_schema.graphql",
  query_path = "tests/unions/union_query.graphql",
  deprecated = "warn"
)]
pub struct UnionQuery;

Valid values are:

  • allow: the response struct fields are not marked as deprecated.
  • warn: the response struct fields are marked as #[deprecated].
  • deny: The struct fields are not included in the response struct andusing them is a compile error.

The default is warn.

Query documents with multiple operations

You can write multiple operations in one query document (one .graphql file). You can then select one by naming the struct you #[derive(GraphQLQuery)] on with the same name as one of the operations. This is neat, as it allows sharing fragments between operations.

Note that the struct and the operation in the GraphQL file must have the same name. We enforce this to make the generated code more predictable.

use graphql_client::GraphQLQuery;

#[derive(GraphQLQuery)]
#[graphql(
    schema_path = "tests/unions/union_schema.graphql",
    query_path = "tests/unions/union_query.graphql",
)]
pub struct UnionQuery;

There is an example in the tests.

Documentation for the generated modules

You can use cargo doc --document-private-items to generate rustdoc documentation on the generated code.

Make cargo recompile when .graphql files have changed

There is an include option you can add to your Cargo.toml. It currently has issues however (see this issue).

Examples

See the examples directory in this repository.

Contributors

Warmest thanks to all those who contributed in any way (not only code) to this project:

  • Alex Vlasov (@indifferentalex)
  • Ben Boeckel (@mathstuf)
  • Chris Fung (@aergonaut)
  • Christian Legnitto (@LegNeato)
  • David Gräff (@davidgraeff)
  • Dirkjan Ochtman (@djc)
  • Fausto Nunez Alberro (@brainlessdeveloper)
  • Hirokazu Hata (@h-michael)
  • Peter Gundel (@peterfication)
  • Sonny Scroggin (@scrogson)
  • Sooraj Chandran (@SoorajChandran)
  • Tom Houlé (@tomhoule)

Code of conduct

Anyone who interacts with this project in any space, including but not limited tothis GitHub repository, must follow our code of conduct.

License

Licensed under either of these:

Contributing

Unless you explicitly state otherwise, any contribution you intentionally submitfor inclusion in the work, as defined in the Apache-2.0 license, shall bedual-licensed as above, without any additional terms or conditions.

  • 注意事项 1.引入jar包版本注意用1.2以上的,1.1没有addObjectParameter方法,对json报文格式处理有欠缺。 org.mountcloud graphql-client 1.2 2.返回的数据格式为map,建议使用阿里大佬开源的fastjson包解析。 代码记录 private final String url = "http:xxxxx"; private final S

 相关资料
  • 快速开始 GraphQL 是一种用于 API 的查询语言。这是 GraphQL 和 REST 之间一个很好的比较 (译者注: GraphQL 替代 REST 是必然趋势)。在这组文章中, 我们不会解释什幺是 GraphQL, 而是演示如何使用 @nestjs/GraphQL 模块。 GraphQLModule 只不过是 Apollo 服务器的包装器。我们没有造轮子, 而是提供一个现成的模块, 这让

  • GraphQL 既是一种用于 API 的查询语言也是一个满足你数据查询的运行时。 GraphQL 对你的 API 中的数据提供了一套易于理解的完整描述,使得客户端能够准确地获得它需要的数据,而且没有任何冗余,也让 API 更容易地随着时间推移而演进,还能用于构建强大的开发者工具。 向你的 API 发出一个 GraphQL 请求就能准确获得你想要的数据,不多不少。 GraphQL 查询总是返回可预测

  • Graphql editor 是一款 Graphql 的可视化编辑器和 IDE,帮助用户更容易理解 GraphQL 模式,通过使用可视化块系统创建模式。GraphQL Editor 将把它们转化为代码。通过 GraphQL Editor,用户可以在不写任何代码的情况下创建可视化的图表,或者以一种很好的方式呈现其模式。 GraphQL View Code Editor View Hierarchy View

  • GraphQL CLI Help us to improve new GraphQL CLI. Check out the new structure and commands below!Feel free to contact us in Discord channel. We would love to hear your feedback. Features Helpful command

  • Fullstack GraphQL Simple Demo Application API built with Node + Express + GraphQL + Sequelize (supports MySQL, Postgres, Sqlite and MSSQL). WebApp built with React + Redux. Written in ES6 using Babel

  • Hasura GraphQL Engine Hasura is an open source product that accelerates API development by 10x by giving you GraphQL or REST APIs with built in authorization on your data, instantly. Read more at hasu