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
#[cfg(test)]
mod tests {
	use super::*;

    #[test]
    fn it_works() {
        assert_eq!(2 + 2, 4);
    }

	#[test]
	fn search_by_title_test(){
		assert_eq!(
		  search_by_title(String::from("shrek")).unwrap().Title,
		  "Shrek"
		);
		assert_eq!(
		  search_by_title(String::from("shrek")).unwrap().Year,
		  "2001"
		);
	}

	#[test]
	fn search_by_id_test(){
		assert_eq!(
		  search_by_id(String::from("tt0126029")).unwrap().Title,
		  "Shrek"
		);
		assert_eq!(
		  search_by_id(String::from("tt0126029")).unwrap().Year,
		  "2001"
		);
	}
}


use serde::{Serialize, Deserialize};
use serde_json;
use reqwest;


/// Structure for holding information about a Film.
///
/// Currently only holds title and year, however to add more fields from the
/// retrieved JSONs should be added. This should be enough, as serde_json pulls
/// every relevant field when populating an instance of Film.
#[derive(Debug, Serialize, Deserialize)]
pub struct Film{
	pub Title: String,
	pub Year: String
}

/// Searches for and returns a film in the OMDb.
///
/// Sends a request to OMDb for a film with the name `title` and returns a Film
/// object populated with the returned information. Does no input validation,
/// formatting, or case-switching, so can be temperamental. Returns a
/// `reqwest::Error` upon failure.
///
/// # Examples
///
/// To search for the film Shrek:
/// ```
/// use omdbrs;
///
/// let shrek: omdbrs::Film = omdbrs::search_by_title(String::from("shrek"))
///   .unwrap();
///
/// assert_eq!(shrek.Title, "Shrek");
/// ```
pub fn search_by_title(title: String) -> Result<Film, reqwest::Error>{
	let mut data = reqwest::get(
	  &format!("http://www.omdbapi.com/?apikey=21e783b3&t={}", title)[..]
	)?;

	Ok(serde_json::from_str(&data.text().unwrap()).unwrap())
}

/// Searches for and returns a film in the OMDb.
///
/// Sends a request to OMDb for a film with the id `id` and returns a Film
/// object populated with the returned information. Does no input validation,
/// formatting, or case-switching, so can be temperamental. Returns a
/// `reqwest::Error` upon failure.
///
/// # Examples
///
/// To search for the film Shrek:
/// ```
/// use omdbrs;
///
/// let shrek: omdbrs::Film = omdbrs::search_by_id(String::from("tt0126029"))
///   .unwrap();
///
/// assert_eq!(shrek.Title, "Shrek");
/// ```
pub fn search_by_id(id: String) -> Result<Film, reqwest::Error>{
	let mut data = reqwest::get(
	  &format!("http://www.omdbapi.com/?apikey=21e783b3&i={}", id)[..]
	)?;

	Ok(serde_json::from_str(&data.text().unwrap()).unwrap())
}