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
use std::collections::HashMap; use reqwest::Url; use serde::Serialize; pub mod body; pub mod objects; pub struct Spotify { pub authorization: String, } pub enum Method { GET, POST, PUT, DELETE, } impl PartialEq for Method { fn eq(&self, other: &Self) -> bool { self == other } } impl Spotify { pub fn new(authorization: &str) -> Self { Spotify { authorization: authorization.to_string(), } } pub fn request<T>( &self, method: Method, url: String, query: Option<HashMap<&str, String>>, body: Option<&T>, ) -> Option<(String, bool)> where T: Serialize + ?Sized, { let url = { if let Some(query) = query { Url::parse_with_params( format!("https://api.spotify.com/v1/{}", url).as_str(), query, ) .unwrap() .to_string() } else { format!("https://api.spotify.com/v1/{}", url) } }; let client = reqwest::blocking::Client::new(); match method { Method::GET => { let response = client .get(url) .header("Accept", "application/json") .header("Content-Type", "application/json") .bearer_auth(self.authorization.as_str()) .send() .unwrap(); if response.status().is_success() { Some((response.text().unwrap(), true)) } else { Some((response.text().unwrap(), false)) } } Method::POST => { client .post(url) .bearer_auth(self.authorization.as_str()) .json(body.unwrap()) .send() .unwrap(); None } Method::PUT => { client .put(url) .bearer_auth(self.authorization.as_str()) .json(body.unwrap()) .send() .unwrap(); None } Method::DELETE => { client .put(url) .bearer_auth(self.authorization.as_str()) .send() .unwrap(); None } } } }