1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
//!
//! # LightQl
//!
//! 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**:
//! ```no_test
//! 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.
//! ```
//!
//! # Usage
//! To use the library there is the `Request` struct that encapsulate the request.
//! ```no_test
//!     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.
//!
//! # From file
//!
//! You can make complexe request request from a file for example:
//! ```no_test
//! let response = Request::from_path("path/to/ql/request.query")
//!     .send::<OnePlayer>("http://your-api/") // Note the turbo-fish
//!     .unwrap();
//! ```
//!
//! # Parameter
//!
//! If you need runtime parameter you can use prepare and an hasmap.
//! ```no_test
//! 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(NotPrepared)
//!
//! ```
#![feature(custom_attribute)]
#![feature(associated_type_defaults)]
#![feature(pattern)]
#![allow(dead_code)]
extern crate mio_httpc;
#[macro_use]
pub extern crate serde_derive;
extern crate serde_json;

mod test;

use mio_httpc::CallBuilder;
pub use serde_json::Value;
use std::collections::HashMap;
use std::error::Error;
use std::fmt;
use std::str::pattern::Pattern;
use mio_httpc::Error as MioError;


#[derive(Debug, PartialEq, Eq)]
/// Define the type of the request.
/// either: a query, a subscription or a mutation.
pub enum QlType {
    Subscribe,
    Query,
    Mutation,
}

#[derive(Debug, Deserialize)]
/// A location in a graphql Error.
pub struct Locations {
    line: u32,
    column: u32,
}

#[derive(Deserialize, Debug)]
/// A Error message that have to be Deserialized.
/// TODO add a pretty print.
pub struct QlErrorInternal {
    message: String,
    locations: Vec<Locations>,
}

#[derive(Debug)]
/// Error type of the crate represent an backendError or a lib usage error.
pub enum QlError {
    NotPrepared,
    EmptyHashmap,
    BadUrl,
    CannotExec(&'static str),
    Internal(Vec<QlErrorInternal>),
}

#[derive(Debug, PartialEq, Eq)]
/// The principal struct of the lib.
/// It's the API that you should use.
/// ```no_test
/// let players: Players = Request::new("{players { uuid }}", QlType::Query)
///     .send("https://your-api-url/"); // Simple inline request.
///
/// let id = 12332;
/// let mut user_id = Hasmap::new();
/// user_id.insert(
///     "_id",
///     id::parse()
/// );
/// let user = Request::from_path("path/to/ql/request.query")
///     .prepare(user_id)
///     .send::<User>("https://your-api-url/"); // Complexe request creation from file.
///
/// ```
pub struct Request {
    data: String,
    ql_type: QlType,
    prepared: bool,
    method: String
}

#[derive(Deserialize, Debug)]
struct QlResponse<T> {
    data: Option<T>,
    errors: Option<Vec<QlErrorInternal>>,
    #[serde(flatten)]
    extra: HashMap<String, Value>,
}

#[derive(Debug)]
/// A wrapper around Request where the type is contained.
pub struct QlRequestTyped<T> {
    t: std::marker::PhantomData<T>,
    request: Request,
}

impl<T> QlRequestTyped<T> {
    /// Create a new typed request.
    pub fn new(query: &str) -> Self {
        Self {
            t: std::marker::PhantomData,
            request: Request::new(query),
        }
    }

    /// Create a typed request from a file path.
    /// The file **have to** end with .(QlType)
    /// `player_request.query` or `player_update.mutation` etc...
    pub fn from_path(name: &str) -> Result<Self, std::io::Error> {
        let request = Request::from_path(name)?;
        Ok(Self {
            t: std::marker::PhantomData,
            request,
        })
    }

    /// prepare the request with a hasmap for each argument
    /// ```no_test
    /// let mut param_map = Hashmap::new();
    /// param_map.insert("_uuid", "The real value");
    /// let response = Request::new("player(uuid: \"_uuid\") { uuid }", QlType::Query)
    ///     .prepare(param_map)
    ///     .send::<Player>()
    ///     .expect("Player cannot be retrieved");
    /// ```
    /// If the is no args to the query the send should detect it, so you don't need to use prepare.
    pub fn prepare(mut self, opt_map: HashMap<String, String>) -> Result<Self, QlError> {
        self.request = self.request.prepare(opt_map)?;
        Ok(self)
    }

    /// Force the preparation in certain case that can be usefull.
    pub fn force_prepare(mut self) -> Self {
        self.request.prepared = true;
        self
    }

    /// The send the request and return the requested type.
    pub fn send(&self, uri: &str) -> Result<T, QlError>
    where
        T: serde::de::DeserializeOwned,
    {
        self.request.send::<T>(uri)
    }
}

impl Request {
    /// Create a new request.
    pub fn new(query: &str) -> Request {
        Request {
            data: String::from(query),
            ql_type: QlType::Query,
            prepared: false,
            method: "POST".to_string()
        }
    }

    /// Get method for the request. Default is post.
    pub fn get(mut self) -> Request {
        self.method = "GET".to_string();
        self
    }

    pub fn post(mut self) -> Request {
        self.method = "POST".to_string();
        self
    }

    /// type of the request. default is query
    pub fn ql_type(mut self, ql_type: QlType) -> Request {
        self.ql_type = ql_type;
        self
    }

    /// Create a request from a file.
    pub fn from_path(name: &str) -> Result<Request, std::io::Error> {
        let request = std::fs::read_to_string(name)?;

        let ql_type = if name.is_suffix_of(".mutation") {
            QlType::Mutation
        } else if name.is_suffix_of(".subscription") {
            QlType::Subscribe
        } else {
            QlType::Query
        };

        Ok(Request {
            data: request,
            ql_type,
            prepared: false,
            method: "POST".to_string()
        })
    }

    /// prepare the request with a hasmap for each argument
    /// ```no_test
    /// let mut param_map = Hashmap::new();
    /// param_map.insert("_uuid", "The real value");
    /// let response = Request::new("player(uuid: \"_uuid\") { uuid }", QlType::Query)
    ///     .prepare(param_map)
    ///     .send::<Player>()
    ///     .expect("Player cannot be retrieved");
    /// ```
    /// If the is no args to the query the send should detect it, so you don't need to use prepare.
    pub fn prepare(mut self, opt_map: HashMap<String, String>) -> Result<Self, QlError> {
        for (key, data) in opt_map {
            self.data = self.data.replace(&key, &data);
        }
        self.prepared = true;
        Ok(self)
    }

    /// Force the preparation in certain case that can be usefull.
    pub fn force_prepare(mut self) -> Self {
        self.prepared = true;
        self
    }

    /// Send need a type to Deserialize the response of the sended request.
    /// you can either use it like:
    /// ```no_test
    /// let player: Player = request.send();
    ///
    /// let player = request.send::<Player>(); // Turbo-fish :D
    /// ```
    pub fn send<T>(&self, uri: &str) -> Result<T, QlError>
        where T: serde::de::DeserializeOwned,
    {
        if !self.prepared && self.param_needed() > 0 {
            return Err(QlError::NotPrepared);
        }
        let res = CallBuilder::new()
            .method(self.method.as_str())
            .body(self.data.clone().into_bytes())
            .header("content-type", "application/graphql")
            .url(uri)?
            .exec()?;
        let string = String::from_utf8(res.1).expect("Cannot stringify");
        let res: QlResponse<T> = serde_json::from_str(&string).expect("Cannot Jsonify");
        if let Some(err) = res.errors {
            Err(QlError::Internal(err))
        } else {
            Ok(res.data.unwrap())
        }
    }

    /// Count the number of param needed by the request.
    pub fn param_needed(&self) -> i32 {
        let mut output = 0;

        for elem in self.data.chars() {
            if elem == ':' {
                output += 1;
            }
        }
        output
    }
}

/// Trait that will be derived in a near future.
pub trait FromQl: serde::de::DeserializeOwned + Sized {
    fn request(_uri: &str, _request: &str, _identifier: &str) -> Option<Self> {
        unimplemented!("TODO implement a derive");
    }
}

// Convert from MioError to QlError.
impl From<MioError> for QlError {
    fn from(error: MioError) -> QlError {
        match error {
            MioError::Httparse(_) => QlError::BadUrl,
            MioError::TimeOut => QlError::CannotExec("Time out"),
            MioError::Url(_) => QlError::BadUrl,
            _ => QlError::CannotExec("Cannot exec")
        }
    }
}

// TODO: increment.
impl fmt::Display for QlError {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        write!(f, "{}", self.description())
    }
}

impl Error for QlError {
    fn description(&self) -> &str {
        match self {
            QlError::NotPrepared => "You should prepare your request before sending it.",
            QlError::EmptyHashmap => "You should replace needed params",
            QlError::Internal(_) => "Internal Error: {}",
            QlError::BadUrl => "Bad url, cannot use it",
            QlError::CannotExec(_) => "Cannot exec this request {}"
        }
    }
}