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
//! This crate wraps Typeform's REST API.
//! Main entry-point is [`Typeform`] - once build it can be used to receive responses.

#![warn(
    anonymous_parameters,
    missing_copy_implementations,
    missing_debug_implementations,
    missing_docs,
    rust_2018_idioms,
    private_doc_tests,
    trivial_casts,
    trivial_numeric_casts,
    unused,
    future_incompatible,
    nonstandard_style,
    unsafe_code,
    unused_import_braces,
    unused_results,
    variant_size_differences
)]

use isahc::{prelude::*, Request};
use serde::Deserialize;

const DEFAULT_TYPEFORM_URL: &str = "https://api.typeform.com";
const GET_FORM_RESPONSES_PATH: &str = "/forms/{form_id}/responses";

/// Main entry point to work with.
#[derive(Debug)]
pub struct Typeform {
    url: String,
    form_id: String,
    token: String,
}

impl Typeform {
    /// Default [`Typeform`] constructor.
    pub fn new(form_id: &str, token: &str) -> Typeform {
        Typeform {
            url: DEFAULT_TYPEFORM_URL.to_string(),
            form_id: form_id.to_string(),
            token: token.to_owned(),
        }
    }

    /// Retrieve all [`Responses`].
    pub fn responses(&self) -> Result<Responses, String> {
        Request::get(format!(
            "{}{}",
            self.url,
            GET_FORM_RESPONSES_PATH.replace("{form_id}", &self.form_id),
        ))
        .header("Authorization", format!("Bearer {}", &self.token))
        .body(())
        .map_err(|error| format!("Failed to build a request: {}", error))?
        .send()
        .map_err(|error| format!("Failed to send get request: {}", error))?
        .json()
        .map_err(|error| format!("Failed to deserialize a response: {}", error))
    }

    /// Retrieve all [`Responses`] which goes after response with [`token`].
    pub fn responses_after(&self, token: &str) -> Result<Responses, String> {
        Request::get(format!(
            "{}{}?after={}&page_size=1",
            self.url,
            GET_FORM_RESPONSES_PATH.replace("{form_id}", &self.form_id),
            token,
        ))
        .header("Authorization", format!("Bearer {}", &self.token))
        .body(())
        .map_err(|error| format!("Failed to build a request: {}", error))?
        .send()
        .map_err(|error| format!("Failed to send get request: {}", error))?
        .json()
        .map_err(|error| format!("Failed to deserialize a response: {}", error))
    }
}

/// Paged list of [`Response`]s.
#[derive(Clone, Debug, Deserialize)]
pub struct Responses {
    /// Total number of items in the retrieved collection.
    total_items: Option<u16>,
    /// Number of pages.
    page_count: Option<u8>,
    /// Array of [Responses](Response).
    pub items: Vec<Response>,
}

/// Unique form's response.
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct Response {
    token: String,
    /// Unique ID for the response. Note that response_id values are unique per form but are not unique globally.
    response_id: Option<String>,
    /// Time of the form landing. In ISO 8601 format, UTC time, to the second, with T as a delimiter between the date and time.
    landed_at: String,
    /// Time that the form response was submitted. In ISO 8601 format, UTC time, to the second, with T as a delimiter between the date and time.
    submitted_at: String,
    /// Metadata about a client's HTTP request.
    metadata: Metadata,
    /// Subset of a complete form definition to be included with a submission.
    definition: Option<Definition>,
    answers: Option<Answers>,
    calculated: Calculated,
}

/// Metadata about a client's HTTP request.
#[derive(Clone, Debug, Deserialize)]
struct Metadata {
    user_agent: String,
    /// Derived from user agent.
    platform: Option<String>,
    referer: String,
    /// IP of the client.
    network_id: String,
}

/// Subset of a complete form definition to be included with a submission.
#[derive(Clone, Debug, Deserialize)]
struct Definition {
    fields: Fields,
}

type Fields = Vec<Field>;

#[derive(Clone, Debug, Deserialize)]
struct Field {
    id: String,
    _type: String,
    title: String,
    description: String,
}

#[derive(Clone, Debug, Deserialize)]
struct Answers(Vec<Answer>);

#[derive(Clone, Debug, Deserialize)]
struct Answer {
    field: AnswerField,
    /// The answer-fields's type.
    #[serde(rename = "type")]
    _type: AnswerType,
    /// Represents single choice answers for dropdown-like fields.
    choice: Option<Choice>,
    /// Represents multiple choice answers.
    choices: Option<Choices>,
    date: Option<String>,
    email: Option<String>,
    file_url: Option<String>,
    number: Option<i32>,
    boolean: Option<bool>,
    text: Option<String>,
    url: Option<String>,
    payment: Option<Payment>,
    phone_number: Option<String>,
}

#[derive(Clone, Debug, Deserialize)]
struct AnswerField {
    /// The unique id of the form field the answer refers to.
    id: String,
    /// The field's type in the original form.
    #[serde(rename = "type")]
    _type: String,
    /// The reference for the question the answer relates to. Use the ref value to match answers with questions. The Responses payload only includes ref for the fields where you specified them when you created the form.
    #[serde(rename = "ref")]
    _ref: String,
    /// The form field's title which the answer is related to.
    title: Option<String>,
}

#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "snake_case")]
enum AnswerType {
    Choice,
    Choices,
    Date,
    Email,
    Url,
    FileUrl,
    Number,
    Boolean,
    Text,
    Payment,
    PhoneNumber,
}

#[derive(Clone, Debug, Deserialize)]
struct Choice {
    label: String,
    other: Option<String>,
}

type Labels = Vec<String>;

#[derive(Clone, Debug, Deserialize)]
struct Choices {
    labels: Labels,
    other: Option<String>,
}

#[derive(Clone, Debug, Deserialize)]
struct Payment {
    amount: String,
    last4: String,
    name: String,
}

#[derive(Clone, Debug, Deserialize)]
struct Calculated {
    score: i32,
}

#[cfg(test)]
mod tests {
    use super::*;

    use std::fs::File;
    use std::io::BufReader;

    #[test]
    fn parse_valid_responses_from_json_should_pass() {
        let file = File::open("tests/typeform_responses.json").expect("Failed to open a file.");
        let reader = BufReader::new(file);
        let _responses: Responses =
            serde_json::from_reader(reader).expect("Failed to build responses from reader.");
    }

    #[test]
    fn parse_valid_responses2_from_json_should_pass() {
        let file = File::open("tests/typeform_responses2.json").expect("Failed to open a file.");
        let reader = BufReader::new(file);
        let _responses: Responses =
            serde_json::from_reader(reader).expect("Failed to build responses from reader.");
    }

    #[test]
    fn parse_valid_responses3_from_json_should_pass() {
        let file = File::open("tests/typeform_responses3.json").expect("Failed to open a file.");
        let reader = BufReader::new(file);
        let _responses: Responses =
            serde_json::from_reader(reader).expect("Failed to build responses from reader.");
    }
}