typeform-rs 0.2.1

REST API client for Typeform written in Rust
Documentation
//! 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 std::io::Read;

use eyre::{Result, WrapErr};
use isahc::{prelude::*, Request};
use serde::{Deserialize, Serialize};

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.")
    }

    /// Retrieves a file uploaded as an answer for a submission.
    ///
    /// [API Reference](https://developer.typeform.com/responses/reference/retrieve-response-file/)
    pub fn response_file(
        &self,
        response_id: String,
        field_id: String,
        filename: String,
    ) -> Result<Vec<u8>> {
        let mut bytes = Vec::new();
        let url = format!(
            "{}{}/{}/fields/{}/files/{}",
            self.url,
            GET_FORM_RESPONSES_PATH.replace("{form_id}", &self.form_id),
            response_id,
            field_id,
            urlencoding::encode(&filename)
        );
        dbg!(&url);
        let _size = Request::get(url)
            .header("Authorization", format!("Bearer {}", &self.token))
            .body(())
            .expect("Failed to build a request.")
            .send()
            .expect("Failed to send get request.")
            .body_mut()
            .read_to_end(&mut bytes)
            .expect("Failed to deserialize a response.");
        Ok(bytes)
    }
}

/// Paged list of [`Response`]s.
#[derive(Clone, Debug, Serialize, 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, Serialize, 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, Serialize, 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, Serialize, Deserialize)]
pub struct Definition {
    pub fields: Fields,
}

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

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

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

#[derive(Clone, Debug, Serialize, 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 => {
                let choice = self.choice.as_ref()?;
                match choice {
                    Choice {
                        label: Some(label), ..
                    } => Some(label.as_str()),
                    Choice {
                        label: None,
                        other: Some(other),
                    } => Some(other.as_str()),
                    _ => None,
                }
            }
            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, Serialize, 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, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AnswerType {
    Choice,
    Choices,
    Date,
    Email,
    Url,
    FileUrl,
    Number,
    Boolean,
    Text,
    Payment,
    PhoneNumber,
}

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

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

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

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

#[derive(Clone, Copy, Debug, Serialize, 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.");
    }

    #[test]
    fn parse_valid_responses4_from_json_should_pass() {
        let file = File::open("tests/typeform_responses4.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 build_request() {
        Request::get(format!("https://api.typeform.com/forms/ED6iRRjj/responses/448xvbqqrfemwrz4cu038448xvqx6d3w/fields/wYuykcQCh8F3/files/{}", urlencoding::encode("860786e2f952-1080х1080.png")))
            .body(())
            .expect("Failed to build a request.");
    }
}