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
//! 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,
    rust_2018_idioms,
    rustdoc::private_doc_tests,
    trivial_casts,
    trivial_numeric_casts,
    unused,
    future_incompatible,
    nonstandard_style,
    unsafe_code,
    unused_import_braces,
    unused_results,
    variant_size_differences
)]

use eyre::{Result, WrapErr};
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`].
    ///
    /// [API Reference](https://developer.typeform.com/responses/reference/retrieve-responses/).
    pub fn responses(&self) -> Result<Responses> {
        Request::get(format!(
            "{}{}",
            self.url,
            GET_FORM_RESPONSES_PATH.replace("{form_id}", &self.form_id),
        ))
        .header("Authorization", format!("Bearer {}", &self.token))
        .body(())
        .wrap_err("Failed to build a request.")?
        .send()
        .wrap_err("Failed to send get request.")?
        .json()
        .wrap_err("Failed to deserialize a response.")
    }

    /// Retrieve all [`Responses`] which goes after response with a [`token`] specified as argument.
    ///
    /// [API Reference](https://developer.typeform.com/responses/reference/retrieve-responses/).
    pub fn responses_after(&self, token: &str) -> Result<Responses> {
        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(())
        .wrap_err("Failed to build a request.")?
        .send()
        .wrap_err("Failed to send get request.")?
        .json()
        .wrap_err("Failed to deserialize a response.")
    }
}

/// Paged list of [`Response`]s.
#[derive(Clone, Debug, Deserialize)]
pub struct Responses {
    /// Total number of items in the retrieved collection.
    pub total_items: Option<u16>,
    /// Number of pages.
    pub 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 {
    /// Each response to your typeform starts with a general data object that includes the token.
    pub token: String,
    /// Unique ID for the response. Note that response_id values are unique per form but are not unique globally.
    pub 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.
    pub 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.
    pub submitted_at: String,
    /// Metadata about a client's HTTP request.
    pub metadata: Metadata,
    /// Subset of a complete form definition to be included with a submission.
    pub definition: Option<Definition>,
    pub answers: Option<Answers>,
    pub calculated: Calculated,
}

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

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

#[derive(Clone, Debug, Deserialize)]
pub struct Fields(Vec<Field>);

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

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

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

impl Answer {
    pub fn as_str(&self) -> Option<&str> {
        match &self._type {
            AnswerType::Text => self.text.as_deref(),
            AnswerType::Url => self.url.as_deref(),
            AnswerType::FileUrl => self.file_url.as_deref(),
            AnswerType::Choice => Some(self.choice.as_ref()?.label.as_str()),
            AnswerType::PhoneNumber => self.phone_number.as_deref(),
            AnswerType::Email => self.email.as_deref(),
            _ => None,
        }
    }
}

impl Answers {
    /// Tries to find an answer based on a [`_ref`] and returns `None` if fails to do it.
    pub fn find(&self, _ref: &str) -> Option<&Answer> {
        self.0.iter().find(|answer| answer.field._ref == _ref)
    }
}

#[derive(Clone, Debug, Deserialize)]
pub struct AnswerField {
    /// The unique id of the form field the answer refers to.
    pub id: String,
    /// The field's type in the original form.
    #[serde(rename = "type")]
    pub _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")]
    pub _ref: String,
    /// The form field's title which the answer is related to.
    pub title: Option<String>,
}

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

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

#[derive(Clone, Debug, Deserialize)]
pub struct Labels(Vec<String>);

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

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

#[derive(Clone, Copy, Debug, Deserialize)]
pub struct Calculated {
    pub 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.");
    }
}