1use std::time::Duration;
4
5use reqwest::Client as HttpClient;
6
7pub use crate::{
8 error::{NewsApiError, Result},
9 models::{ApiResponse, SourceDetail, SourcesResponse, SuccessResponse},
10 params::{EverythingParams, SourceParams, TopHeadlinesParams},
11 version::ApiVersion,
12};
13
14const BASE_URL: &str = "https://newsapi.org";
15
16#[derive(Debug, Clone)]
36pub struct NewsApiClient {
37 api_key: String,
38 timeout: Duration,
39 http: HttpClient,
40 version: ApiVersion,
41}
42
43impl NewsApiClient {
44 pub fn new(api_key: impl Into<String>) -> Self {
48 Self::with_config(api_key, Duration::from_secs(30), ApiVersion::default())
49 }
50
51 pub fn with_config(api_key: impl Into<String>, timeout: Duration, version: ApiVersion) -> Self {
53 let http = HttpClient::builder()
54 .timeout(timeout)
55 .build()
56 .expect("Failed to build HTTP client");
57
58 Self {
59 http,
60 api_key: api_key.into(),
61 version,
62 timeout,
63 }
64 }
65
66 pub fn with_timeout(api_key: impl Into<String>, timeout: Duration) -> Self {
68 Self::with_config(api_key, timeout, ApiVersion::V2)
69 }
70
71 pub fn with_version(api_key: impl Into<String>, version: ApiVersion) -> Self {
73 Self::with_config(api_key, Duration::from_secs(30), version)
74 }
75
76 pub fn set_version(&mut self, version: ApiVersion) {
78 self.version = version;
79 }
80
81 pub fn version(&self) -> ApiVersion {
83 self.version
84 }
85
86 pub fn set_timeout(&mut self, timeout: Duration) -> Result<()> {
88 let new_http = HttpClient::builder()
89 .timeout(timeout)
90 .build()
91 .map_err(|e| NewsApiError::Request(e.into()))?;
92 self.http = new_http;
93 self.timeout = timeout;
94 Ok(())
95 }
96
97 fn build_url(&self, endpoint: &str) -> String {
99 format!("{}{}/{}", BASE_URL, self.version.path(), endpoint)
100 }
101
102 async fn execute_request(
104 &self,
105 request: reqwest::RequestBuilder,
106 timeout: Option<Duration>,
107 ) -> Result<reqwest::Response> {
108 let request = if let Some(t) = timeout {
109 request.timeout(t)
110 } else {
111 request
112 };
113 request.send().await.map_err(|e| {
114 if e.is_timeout() {
115 let actual_timeout = timeout.unwrap_or(self.timeout);
116 NewsApiError::Timeout(actual_timeout)
117 } else {
118 NewsApiError::Request(e)
119 }
120 })
121 }
122
123 async fn handle_response(&self, response: reqwest::Response) -> Result<SuccessResponse> {
125 let body = response.bytes().await?;
126 let api_response: ApiResponse = serde_json::from_slice(&body)?;
127 match api_response {
128 ApiResponse::Success(success) => Ok(success),
129 ApiResponse::Error(error) => {
130 if error.code == "rateLimited" {
131 Err(NewsApiError::RateLimitExceeded)
132 } else if error.code == "apiKeyInvalid" {
133 Err(NewsApiError::InvalidApiKey)
134 } else {
135 Err(NewsApiError::Api {
136 code: error.code,
137 message: error.message,
138 })
139 }
140 }
141 ApiResponse::Unknown => Err(NewsApiError::InvalidParams(
142 "Unexpected response format".into(),
143 )),
144 }
145 }
146
147 pub async fn top_headlines(&self, params: &TopHeadlinesParams) -> Result<SuccessResponse> {
155 self.top_headlines_with_timeout(params, None).await
156 }
157
158 pub async fn top_headlines_with_timeout(
167 &self,
168 params: &TopHeadlinesParams,
169 timeout: Option<Duration>,
170 ) -> Result<SuccessResponse> {
171 let mut query = vec![("apiKey", self.api_key.to_string())];
172
173 if let Some(country) = ¶ms.country {
174 query.push(("country", country.to_string()));
175 }
176
177 if let Some(category) = ¶ms.category {
178 query.push(("category", category.to_string()));
179 }
180
181 if let Some(sources) = ¶ms.sources {
182 query.push(("sources", sources.to_string()));
183 }
184
185 if let Some(q) = ¶ms.q {
186 query.push(("q", q.to_string()));
187 }
188
189 if let Some(page) = params.page {
190 query.push(("page", page.to_string()));
191 }
192
193 if let Some(page_size) = params.page_size {
194 query.push(("pageSize", page_size.to_string()));
195 }
196
197 let url = self.build_url("/top-headlines");
198 let request = self.http.get(&url).query(&query);
199 let response = self.execute_request(request, timeout).await?;
200 self.handle_response(response).await
201 }
202
203 pub async fn everything(&self, params: &EverythingParams) -> Result<SuccessResponse> {
211 self.everything_with_timeout(params, None).await
212 }
213
214 pub async fn everything_with_timeout(
223 &self,
224 params: &EverythingParams,
225 timeout: Option<Duration>,
226 ) -> Result<SuccessResponse> {
227 let mut query = vec![("apiKey", self.api_key.to_string())];
228 if let Some(q) = ¶ms.q {
229 query.push(("q", q.to_string()));
230 }
231
232 if let Some(q_in_title) = ¶ms.q_in_title {
233 query.push(("qInTitle", q_in_title.to_string()));
234 }
235
236 if let Some(sources) = ¶ms.sources {
237 query.push(("sources", sources.to_string()));
238 }
239
240 if let Some(domains) = ¶ms.domains {
241 query.push(("domains", domains.to_string()));
242 }
243
244 if let Some(from) = ¶ms.from {
245 query.push(("from", from.to_string()));
246 }
247
248 if let Some(to) = ¶ms.to {
249 query.push(("to", to.to_string()));
250 }
251
252 if let Some(language) = ¶ms.language {
253 query.push(("language", language.to_string()));
254 }
255
256 if let Some(sort_by) = ¶ms.sort_by {
257 query.push(("sortBy", sort_by.to_string()));
258 }
259
260 if let Some(page) = params.page {
261 query.push(("page", page.to_string()));
262 }
263
264 if let Some(page_size) = params.page_size {
265 query.push(("pageSize", page_size.to_string()));
266 }
267
268 let url = self.build_url("/everything");
269 let request = self.http.get(&url).query(&query);
270 let response = self.execute_request(request, timeout).await?;
271 self.handle_response(response).await
272 }
273
274 pub async fn sources(&self, params: &SourceParams) -> Result<Vec<SourceDetail>> {
282 self.sources_with_timeout(params, None).await
283 }
284
285 pub async fn sources_with_timeout(
294 &self,
295 params: &SourceParams,
296 timeout: Option<Duration>,
297 ) -> Result<Vec<SourceDetail>> {
298 let mut query = vec![("apiKey", self.api_key.to_string())];
299
300 if let Some(category) = ¶ms.category {
301 query.push(("category", category.to_string()));
302 }
303
304 if let Some(language) = ¶ms.language {
305 query.push(("language", language.to_string()));
306 }
307
308 if let Some(country) = ¶ms.country {
309 query.push(("country", country.to_string()));
310 }
311
312 let url = self.build_url("/sources");
313 let request = self.http.get(&url).query(&query);
314 let response = self.execute_request(request, timeout).await?;
315 let body = response.bytes().await?;
316
317 let source_resp: SourcesResponse = serde_json::from_slice(&body)?;
318 match source_resp {
319 SourcesResponse::Ok { sources } => Ok(sources),
320 SourcesResponse::Err(err) => Err(NewsApiError::Api {
321 code: err.code,
322 message: err.message,
323 }),
324 SourcesResponse::Unknown => Err(NewsApiError::InvalidParams(
325 "Unknown response from sources endpoint".into(),
326 )),
327 }
328 }
329}