Crates.io | lightql |
lib.rs | lightql |
version | 0.2.0 |
source | src |
created_at | 2018-12-05 17:21:16.628284 |
updated_at | 2018-12-06 13:27:18.753735 |
description | lightweight graphql request builder. |
homepage | |
repository | https://github.com/Afourcat/LightQl |
max_upload_size | |
id | 100271 |
size | 29,874 |
This library is a lightweight library that let you make graphql request and serialize them into the given type. The fields of the given type should match with the "data" content of the reponses. Examples:
use lightql::{Request, QlType};
let response = json!(
"data": {
"players": [
{
"id": 1,
"name": "fred"
},
{
"id": 2,
"name": "marcel"
},
{
"id": 3,
"name": "roger"
}
]
}
)
// The given type should look like that:
#[derive(Deserialize)]
struct Player {
#[serde(default = "get_default_id")]
id: i32,
name: String
}
#[derive(Deserialize)]
struct Players {
players: Vec<Player>
}
// This will work.
// But here if you want to request one player:
let response = json!(
"data": {
"player": {
"id": 4,
"name": "bouras"
}
}
);
#[derive(Deserialize)]
struct OnePlayer {
player: Player
}
// default function
fn get_default_id() -> i32 {
0
}
// You have to match the "data" content with field.
To use the library there is the Request
struct that encapsulate the request.
let player: OnePlayer = Request::new("player(id: 1) { name }", QlType::Query)
.send("https://your-api/")
.expect("Cannot fetch player");
// print: Player { id: 0, name: "fred" }
println!("{:?}", player);
Send automatically infer type of deserialisation.
You can make complexe request request from a file for example:
let response = Request::from_path("path/to/ql/request.query")
.send::<OnePlayer>("http://your-api/") // Note the turbo-fish
.unwrap();
If you need runtime parameter you can use prepare and an hasmap.
let user_id = get_user_id(&user);
let mut params = Hasmap::new();
params.insert(
"_id",
user_id.parse()
);
let response = Request::new("player(id: _id) { id, name }", QlType::Query)
.prepare(Some(params)) // Should prepare before sending !
.send::<OnePlayer>("https://your-api/")
.unwrap(); // If not prepared return Err(QlNotPrepared)
You can post issues and pull requests I will read them. Please respect the Rust style.