async-graphql/docs/zh-CN/src/quickstart.md
Edward Rudd 3b7ed74d11 correct doc examples so they compile
- examples to fix still
  - error_extensions.md ResultExt example does not compile!
     - trait ErrorExtensions is not implemented for ParseIntError
  - dataloader
     - requires sqlx to work. So we either "stub" it OR we rewrite them simpler to use a  simple "faux" db library
2022-06-02 17:32:12 -04:00

1.7 KiB
Raw Blame History

快速开始

添加依赖

[dependencies]
async-graphql = "4.0"
async-graphql-actix-web = "4.0" # 如果你需要集成到Actix-web
async-graphql-warp = "4.0" # 如果你需要集成到Warp
async-graphql-tide = "4.0" # 如果你需要集成到Tide

写一个Schema

一个GraphQL的Schema包含一个必须的查询(Query)根对象,可选的变更(Mutation)根对象和可选的订阅(Subscription)根对象这些对象类型都是用Rust语言的结构来描述它们结构的字段对应GraphQL对象的字段。

Async-graphql实现了常用数据类型到GraphQL类型的映射例如i32, f64, Option<T>, Vec<T>等。同时,你也能够扩展这些基础类型基础数据类型在GraphQL里面称为标量。

下面是一个简单的例子,我们只提供一个查询,返回ab的和。

# extern crate async_graphql;
use async_graphql::*;

struct Query;

#[Object]
impl Query {
    /// Returns the sum of a and b
    async fn add(&self, a: i32, b: i32) -> i32 {
        a + b
    }
}

执行查询

在我们这个例子里面只有Query没有Mutation和Subscription所以我们用EmptyMutationEmptySubscription来创建Schema然后调用Schema::execute来执行查询。

# extern crate async_graphql;
# use async_graphql::*;
#
# struct Query;
# #[Object]
# impl Query {
#   async fn version(&self) -> &str { "1.0" }    
# }
# async fn other() {
let schema = Schema::new(Query, EmptyMutation, EmptySubscription);
let res = schema.execute("{ add(a: 10, b: 20) }").await;
# }

把查询结果输出为JSON

let json = serde_json::to_string(&res);

和Web Server的集成

请参考https://github.com/async-graphql/examples