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
//! Service to send HTTP-request to a server.

use super::Task;
use crate::callback::Callback;
use crate::format::{Binary, Format, Text};
use failure::Fail;
use serde::Serialize;
use std::collections::HashMap;
use stdweb::serde::Serde;
use stdweb::unstable::{TryFrom, TryInto};
use stdweb::web::ArrayBuffer;
use stdweb::{JsSerialize, Value};
#[allow(unused_imports)]
use stdweb::{_js_impl, js};

pub use http::{HeaderMap, Method, Request, Response, StatusCode, Uri};

/// Type to set cache for fetch.
#[derive(Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum Cache {
    /// `default` value of cache.
    #[serde(rename = "default")]
    DefaultCache,
    /// `no-store` value of cache.
    NoStore,
    /// `reload` value of cache.
    Reload,
    /// `no-cache` value of cache.
    NoCache,
    /// `force-cache` value of cache
    ForceCache,
    /// `only-if-cached` value of cache
    OnlyIfCached,
}

/// Type to set credentials for fetch.
#[derive(Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum Credentials {
    /// `omit` value of credentials.
    Omit,
    /// `include` value of credentials.
    Include,
    /// `same-origin` value of credentials.
    SameOrigin,
}

/// Type to set mode for fetch.
#[derive(Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum Mode {
    /// `same-origin` value of mode.
    SameOrigin,
    /// `no-cors` value of mode.
    NoCors,
    /// `cors` value of mode.
    Cors,
}

/// Type to set redirect behaviour for fetch.
#[derive(Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum Redirect {
    /// `follow` value of redirect.
    Follow,
    /// `error` value of redirect.
    Error,
    /// `manual` value of redirect.
    Manual,
}

/// Init options for `fetch()` function call.
/// https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
#[derive(Serialize, Default)]
pub struct FetchOptions {
    /// Cache of a fetch request.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cache: Option<Cache>,
    /// Credentials of a fetch request.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub credentials: Option<Credentials>,
    /// Redirect behaviour of a fetch request.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub redirect: Option<Redirect>,
    /// Request mode of a fetch request.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mode: Option<Mode>,
}

/// Represents errors of a fetch service.
#[derive(Debug, Fail)]
enum FetchError {
    #[fail(display = "failed response")]
    FailedResponse,
}

/// A handle to control sent requests. Can be canceled with a `Task::cancel` call.
#[must_use]
pub struct FetchTask(Option<Value>);

/// A service to fetch resources.
#[derive(Default)]
pub struct FetchService {}

impl FetchService {
    /// Creates a new service instance connected to `App` by provided `sender`.
    pub fn new() -> Self {
        Self {}
    }

    /// Sends a request to a remote server given a Request object and a callback
    /// fuction to convert a Response object into a loop's message.
    ///
    /// You may use a Request builder to build your request declaratively as on the
    /// following examples:
    ///
    /// ```rust
    ///    let post_request = Request::post("https://my.api/v1/resource")
    ///            .header("Content-Type", "application/json")
    ///            .body(Json(&json!({"foo": "bar"})))
    ///            .expect("Failed to build request.");
    ///
    ///    let get_request = Request::get("https://my.api/v1/resource")
    ///            .body(Nothing)
    ///            .expect("Failed to build request.");
    /// ```
    ///
    /// The callback function can build a loop message by passing or analizing the
    /// response body and metadata.
    ///
    /// ```rust
    ///     context.web.fetch(
    ///         post_request,
    ///         |response| {
    ///             if response.status().is_success() {
    ///                 Msg::Noop
    ///             } else {
    ///                 Msg::Error
    ///             }
    ///         }
    ///     )
    /// ```
    ///
    /// One can also simply consume and pass the response or body object into
    /// the message.
    ///
    /// ```rust
    ///     context.web.fetch(
    ///         get_request,
    ///         |response| {
    ///             let (meta, Json(body)) = response.into_parts();
    ///             if meta.status.is_success() {
    ///                 Msg::FetchResourceComplete(body)
    ///             } else {
    ///                 Msg::FetchResourceFailed
    ///             }
    ///         }
    ///     )
    /// ```
    ///
    pub fn fetch<IN, OUT: 'static>(
        &mut self,
        request: Request<IN>,
        callback: Callback<Response<OUT>>,
    ) -> FetchTask
    where
        IN: Into<Text>,
        OUT: From<Text>,
    {
        fetch_impl::<IN, OUT, String, String>(false, request, None, callback)
    }

    /// `fetch` with provided `FetchOptions` object.
    /// Use it if you need to send cookies with a request:
    /// ```rust
    ///     let request = fetch::Request::get("/path/")
    ///         .body(Nothing).unwrap();
    ///     let options = FetchOptions {
    ///         credentials: Some(Credentials::SameOrigin),
    ///         ..FetchOptions::default()
    ///     };
    ///     let task = fetch_service.fetch_with_options(request, options, callback);
    /// ```
    pub fn fetch_with_options<IN, OUT: 'static>(
        &mut self,
        request: Request<IN>,
        options: FetchOptions,
        callback: Callback<Response<OUT>>,
    ) -> FetchTask
    where
        IN: Into<Text>,
        OUT: From<Text>,
    {
        fetch_impl::<IN, OUT, String, String>(false, request, Some(options), callback)
    }

    /// Fetch the data in binary format.
    pub fn fetch_binary<IN, OUT: 'static>(
        &mut self,
        request: Request<IN>,
        callback: Callback<Response<OUT>>,
    ) -> FetchTask
    where
        IN: Into<Binary>,
        OUT: From<Binary>,
    {
        fetch_impl::<IN, OUT, Vec<u8>, ArrayBuffer>(true, request, None, callback)
    }

    /// Fetch the data in binary format.
    pub fn fetch_binary_with_options<IN, OUT: 'static>(
        &mut self,
        request: Request<IN>,
        options: FetchOptions,
        callback: Callback<Response<OUT>>,
    ) -> FetchTask
    where
        IN: Into<Binary>,
        OUT: From<Binary>,
    {
        fetch_impl::<IN, OUT, Vec<u8>, ArrayBuffer>(true, request, Some(options), callback)
    }
}

fn fetch_impl<IN, OUT: 'static, T, X>(
    binary: bool,
    request: Request<IN>,
    options: Option<FetchOptions>,
    callback: Callback<Response<OUT>>,
) -> FetchTask
where
    IN: Into<Format<T>>,
    OUT: From<Format<T>>,
    T: JsSerialize,
    X: TryFrom<Value> + Into<T>,
{
    // Consume request as parts and body.
    let (parts, body) = request.into_parts();

    // Map headers into a Js serializable HashMap.
    let header_map: HashMap<&str, &str> = parts
        .headers
        .iter()
        .map(|(k, v)| {
            (
                k.as_str(),
                v.to_str().unwrap_or_else(|_| {
                    panic!("Unparsable request header {}: {:?}", k.as_str(), v)
                }),
            )
        })
        .collect();

    // Formats URI.
    let uri = format!("{}", parts.uri);
    let method = parts.method.as_str();
    let body = body.into().ok();

    // Prepare the response callback.
    // Notice that the callback signature must match the call from the javascript
    // side. There is no static check at this point.
    let callback = move |success: bool, status: u16, headers: HashMap<String, String>, data: X| {
        let mut response_builder = Response::builder();
        response_builder.status(status);
        for (key, values) in &headers {
            response_builder.header(key.as_str(), values.as_str());
        }

        // Deserialize and wrap response data into a Text object.
        let data = if success {
            Ok(data.into())
        } else {
            Err(FetchError::FailedResponse.into())
        };
        let out = OUT::from(data);
        let response = response_builder.body(out).unwrap();
        callback.emit(response);
    };

    let handle = js! {
        var body = @{body};
        if (@{binary} && body != null) {
            body = Uint8Array.from(body);
        }
        var data = {
            method: @{method},
            body: body,
            headers: @{header_map},
        };
        var request = new Request(@{uri}, data);
        var callback = @{callback};
        var abortController = AbortController ? new AbortController() : null;
        var handle = {
            active: true,
            callback,
            abortController,
        };
        var init = @{Serde(options)} || {};
        if (abortController && !("signal" in init)) {
            init.signal = abortController.signal;
        }
        fetch(request, init).then(function(response) {
            var promise = (@{binary}) ? response.arrayBuffer() : response.text();
            var status = response.status;
            var headers = {};
            response.headers.forEach(function(value, key) {
                headers[key] = value;
            });
            promise.then(function(data) {
                if (handle.active == true) {
                    handle.active = false;
                    callback(true, status, headers, data);
                    callback.drop();
                }
            }).catch(function(err) {
                if (handle.active == true) {
                    handle.active = false;
                    callback(false, status, headers, data);
                    callback.drop();
                }
            });
        }).catch(function(e) {
            if (handle.active == true) {
                var data = (@{binary}) ? new ArrayBuffer() : "";
                handle.active = false;
                callback(false, 408, {}, data);
                callback.drop();
            }
        });
        return handle;
    };
    FetchTask(Some(handle))
}

impl Task for FetchTask {
    fn is_active(&self) -> bool {
        if let Some(ref task) = self.0 {
            let result = js! {
                var the_task = @{task};
                return the_task.active &&
                        (!the_task.abortController || !the_task.abortController.signal.aborted);
            };
            result.try_into().unwrap_or(false)
        } else {
            false
        }
    }
    fn cancel(&mut self) {
        // Fetch API doesn't support request cancelling in all browsers
        // and we should use this workaround with a flag.
        // In that case, request not canceled, but callback won't be called.
        let handle = self
            .0
            .take()
            .expect("tried to cancel request fetching twice");
        js! {  @(no_return)
            var handle = @{handle};
            handle.active = false;
            handle.callback.drop();
            if (handle.abortController) {
                handle.abortController.abort();
            }
        }
    }
}

impl Drop for FetchTask {
    fn drop(&mut self) {
        if self.is_active() {
            self.cancel();
        }
    }
}