1use crate::endpoints;
2use crate::endpoints::join_thscodes;
3use crate::types::TEN_YEARS_MS;
4use crate::{
5 Client, Error, IndexCatalogData, IndexConstituentsData, IndexHistoricalData, IndexTag,
6 PriceSnapshotData, Response, Thscode, UnixMillis, ValidationError,
7};
8
9impl Client {
10 #[doc = concat!(
14 "```no_run\n",
15 include_str!("../examples/index_catalog_ths_index_list.rs"),
16 "\n```"
17 )]
18 pub async fn index_catalog_ths_index_list(
19 &self,
20 tag: IndexTag,
21 ) -> Result<Response<IndexCatalogData>, Error> {
22 self.get(endpoints::INDEX_CATALOG, &[("tag", tag.to_string())])
23 .await
24 }
25
26 #[doc = concat!(
30 "```no_run\n",
31 include_str!("../examples/index_constituents_ths_stock_list.rs"),
32 "\n```"
33 )]
34 pub async fn index_constituents_ths_stock_list(
35 &self,
36 thscode: impl TryInto<Thscode, Error: Into<ValidationError>>,
37 ) -> Result<Response<IndexConstituentsData>, Error> {
38 let thscode: Thscode = thscode.try_into().map_err(Into::into)?;
39 self.get(
40 endpoints::INDEX_CONSTITUENTS,
41 &[("thscode", thscode.as_str())],
42 )
43 .await
44 }
45
46 #[doc = concat!(
50 "```no_run\n",
51 include_str!("../examples/index_prices_snapshot.rs"),
52 "\n```"
53 )]
54 pub async fn index_prices_snapshot(
55 &self,
56 thscodes: impl IntoIterator<Item = impl TryInto<Thscode, Error: Into<ValidationError>>>,
57 ) -> Result<Response<PriceSnapshotData>, Error> {
58 self.get(
59 endpoints::INDEX_SNAPSHOT,
60 &[("thscodes", join_thscodes(thscodes, None)?)],
61 )
62 .await
63 }
64
65 #[doc = concat!(
69 "```no_run\n",
70 include_str!("../examples/index_prices_historical.rs"),
71 "\n```"
72 )]
73 pub async fn index_prices_historical(
74 &self,
75 thscode: impl TryInto<Thscode, Error: Into<ValidationError>>,
76 start: impl TryInto<UnixMillis, Error: Into<ValidationError>>,
77 end: impl TryInto<UnixMillis, Error: Into<ValidationError>>,
78 ) -> Result<Response<IndexHistoricalData>, Error> {
79 let thscode: Thscode = thscode.try_into().map_err(Into::into)?;
80 let start: UnixMillis = start.try_into().map_err(Into::into)?;
81 let end: UnixMillis = end.try_into().map_err(Into::into)?;
82 validate_history_window(start, end)?;
83 let query = [
84 ("thscode", thscode.into_string()),
85 ("interval", "1d".to_owned()),
86 ("start", start.to_string()),
87 ("end", end.to_string()),
88 ];
89 self.get(endpoints::INDEX_HISTORICAL, &query).await
90 }
91}
92
93fn validate_history_window(start: UnixMillis, end: UnixMillis) -> Result<(), ValidationError> {
94 if end < start {
95 return Err(ValidationError::new(
96 "end",
97 "must not be earlier than start",
98 ));
99 }
100 if end.get() - start.get() > TEN_YEARS_MS {
101 return Err(ValidationError::new(
102 "end",
103 "requested time window exceeds ten years",
104 ));
105 }
106 Ok(())
107}
108
109#[cfg(test)]
110mod tests {
111 use std::rc::Rc;
112
113 use super::*;
114 use crate::ApiKey;
115
116 struct LocalThscode(Rc<str>);
117
118 impl TryFrom<LocalThscode> for Thscode {
119 type Error = ValidationError;
120
121 fn try_from(value: LocalThscode) -> Result<Self, Self::Error> {
122 Self::new(value.0)
123 }
124 }
125
126 #[test]
127 fn historical_window_enforces_order_and_ten_year_limit() {
128 let start = UnixMillis::new(1_000_000_000_000).unwrap();
129 let before_start = UnixMillis::new(start.get() - 1).unwrap();
130 let limit = UnixMillis::new(start.get() + TEN_YEARS_MS).unwrap();
131 let after_limit = UnixMillis::new(limit.get() + 1).unwrap();
132
133 assert!(validate_history_window(start, before_start).is_err());
134 assert!(validate_history_window(start, limit).is_ok());
135 assert!(validate_history_window(start, after_limit).is_err());
136 }
137
138 #[tokio::test]
139 async fn historical_prices_keeps_window_validation_on_its_call_edge() {
140 let client = Client::builder(ApiKey::new("test-api-key").unwrap())
141 .base_url("http://127.0.0.1:9")
142 .build()
143 .unwrap();
144 let index = Thscode::new("000300.SH").unwrap();
145 let start = UnixMillis::new(1_000_000_000_000).unwrap();
146 let invalid_ends = [
147 UnixMillis::new(start.get() - 1).unwrap(),
148 UnixMillis::new(start.get() + TEN_YEARS_MS + 1).unwrap(),
149 ];
150
151 for end in invalid_ends {
152 let error = client
153 .index_prices_historical(&index, start.get(), end.get())
154 .await
155 .unwrap_err();
156 assert!(matches!(error, Error::InvalidInput(_)));
157 }
158 }
159
160 #[tokio::test(flavor = "current_thread")]
161 async fn endpoint_input_does_not_require_send() {
162 let client = Client::builder(ApiKey::new("test-api-key").unwrap())
163 .base_url("http://127.0.0.1:9")
164 .build()
165 .unwrap();
166
167 let error = client
168 .index_constituents_ths_stock_list(LocalThscode(Rc::from("invalid")))
169 .await
170 .unwrap_err();
171
172 assert!(matches!(error, Error::InvalidInput(_)));
173 }
174}