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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use crate::common::{config::Config, http::ResponseSchema};
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct Page {
#[serde(rename = "pageNum")]
pub page_num: usize,
#[serde(rename = "pageSize")]
pub page_size: usize,
///The total number of records that meet the filter criteria.
pub records: Vec<Record>,
///The actual number of records returned per page.If 'pageSize=100' is specified when requesting, but the actual number of records is only 35, 35 is returned.
pub total: usize,
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct Record {
///record ID
#[serde(rename = "recordId")]
pub record_id: String,
///The creation time of the record, in timestamp format
#[serde(rename = "createdAt")]
pub created_at: usize,
///The modification time of the record, in timestamp format
#[serde(rename = "updatedAt")]
pub updated_at: usize,
///The data of the corresponding field in a record, the return format is {'fieldName': 'fielValue'}, please refer to Record for details
pub fields: FieldContext,
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct FieldContext {
#[serde(flatten)]
pub fields: HashMap<String, serde_json::Value>,
}
pub struct RecordsManager {
pub space_id: String,
pub datasheet_id: String,
pub view_id: Option<String>,
pub config: Config,
}
impl RecordsManager {
pub async fn query_all(&self) -> anyhow::Result<Vec<Record>> {
let url = format!(
"{}/datasheets/{}/records",
self.config.get_url(),
self.datasheet_id
);
let client = reqwest::Client::new();
let resp = client
.get(&url)
.headers(self.config.clone().into())
.send()
.await?
.json::<ResponseSchema<Page>>()
.await?;
match resp.code {
200 => anyhow::Ok(resp.data.unwrap().records),
_ => Err(anyhow::Error::msg(format!(
"code: {}, success: {}, message: {}, request_url: {}",
resp.code, resp.success, resp.message, url
))),
}
}
pub async fn query_with_params(
&self,
query_params: &QueryParameters,
) -> anyhow::Result<Vec<Record>> {
let url = format!(
"{}/datasheets/{}/records{}",
self.config.clone().get_url(),
self.datasheet_id.clone(),
query_params
);
let client = reqwest::Client::new();
let resp = client
.get(&url)
.headers(self.config.clone().into())
.send()
.await?
.json::<ResponseSchema<Page>>()
.await?;
match resp.code {
200 => anyhow::Ok(resp.data.unwrap().records),
_ => Err(anyhow::Error::msg(format!(
"code: {}, success: {}, message: {}, request_url: {}",
resp.code,
resp.success,
resp.message,
format!("{}", url)
))),
}
}
}
#[derive(Debug)]
pub struct QueryParameters {
///How many records are returned per page. By default, 100 records are returned per page. The value range is an integer from 1 to 1000.```
pub page_size: Option<usize>,
///How many records are returned in total. If maxRecords and pageSize are used at the same time, and the value of maxRecords is less than the total number of records, only the setting of maxRecords will take effect.
pub max_records: Option<usize>,
///Default: 1
/// Example: pageNum=1
/// Specifies the page number of the page, which is used in conjunction with the pageSize parameter. For example, `pageSize=1000&pageNum=2` returns records between 1001 and 2000.
pub page_num: Option<usize>,
///Sort the returned records. Sort is an array of multiple sort objects.The structure of a single sort object is `{"order":"asc or desc", "field":"Field name or field ID"}`.Query Example `sort[][field]=Customer Name&sort[][order]=asc`,The returned records are sorted alphabetically in the Customer Name column.If sort and viewId are used at the same time, the sort condition specified by sort will overwrite the sort condition in the view.
pub sort: Option<Vec<HashMap<String, String>>>,
///Example: `recordIds=rec4zxfWB5uyM`
///Returns a specified record. Example of obtaining multiple records:`&recordIds=rec4zxfWB5uyM&,reclNflLgtzjY`. The returned results are sorted according to the order in which the recordIds are passed in. No paging, up to 1000 records can be returned each time.
pub record_ids: Option<Vec<String>>,
///Example: `viewId=viwG9l1VPD6nH`
///When the viewId is not explicitly specified, all records and fields are returned.When the viewId is explicitly specified, all records in the specified view will be returned in turn according to the sorting in the specified view.Note that the hidden fields in the view will not appear in the returned results.
pub view_id: Option<String>,
///The returned record results are limited to the specified fields.cURL Query Example. 1. &fields=name,age (when &fieldKey=name) 2. &fields=fldWooy3c3Puz,fldEAr5y7Go5S (when &fieldKey=id).Both of the above two writing methods specify that the returned record only contains two columns 「Name」 and 「Age」.
pub fields: Option<Vec<String>>,
///Use smart formulas to filter records.The formula can be used for reference《Formula Overview》.If filterByFormula and viewId are used at the same time, all records in the specified view that meet this formula will be returned.Query Example. &filterByFormula={Title}="tittle 1"(You need to use the encodeURIComponent() function to escape the '{Title}="Heading 1"'.) You can accurately match the record with the value of "Heading 1" in the "Heading" column.
pub filter_by_formula: Option<String>,
///Default: "json"
/// Enum: "string" "json"
/// The type of the value in the cell. The default is json. When string is specified, all values will be automatically converted to string format. When string is specified, if the returned records contain date-time values, these values will use the time zone given in the following order (priority from high to low):
/// If the date-time field has set a time zone, use that one.
/// If the user has set a time zone in user settings, use that one.
/// Use the default time zone (UTC-5, America/Toronto).
pub cell_format: Option<String>,
///Default: `"name"`
/// Enum: `"name"` `"id"`
/// The key used when querying fields and returning fields. The default is' name '(field name). When 'id' is specified, fieldId will be used as the query and return method (use 'id' can avoid code invalidation caused by modifying field names).
pub field_key: FieldKey,
}
impl Default for QueryParameters {
fn default() -> Self {
Self {
page_size: Some(1000),
max_records: Some(100000),
page_num: Some(1),
sort: None,
record_ids: None,
view_id: None,
fields: None,
filter_by_formula: None,
cell_format: None,
field_key: FieldKey::default(),
}
}
}
impl QueryParameters {
pub fn new() -> Self {
Self {
..Default::default()
}
}
pub fn set_page_size(&mut self, page_size: Option<usize>) {
self.page_size = page_size;
}
pub fn set_max_records(&mut self, max_records: Option<usize>) {
self.max_records = max_records;
}
pub fn set_page_num(&mut self, page_num: Option<usize>) {
self.page_num = page_num;
}
pub fn set_sort(&mut self, sort: Option<Vec<HashMap<String, String>>>) {
self.sort = sort;
}
pub fn set_record_ids(&mut self, record_ids: Option<Vec<String>>) {
self.record_ids = record_ids;
}
pub fn set_view_id(&mut self, view_id: Option<String>) {
self.view_id = view_id;
}
pub fn set_fields(&mut self, fields: Option<Vec<String>>) {
self.fields = fields;
}
pub fn set_filter_by_formula(&mut self, filter_by_formula: Option<String>) {
self.filter_by_formula = filter_by_formula;
}
pub fn set_cell_format(&mut self, cell_format: Option<String>) {
self.cell_format = cell_format;
}
pub fn set_field_key(&mut self, field_key: FieldKey) {
self.field_key = field_key;
}
pub fn get_params_string(&self) -> String {
format!("{}", self)
}
}
impl std::fmt::Display for QueryParameters {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "?fieldKey={}", self.field_key)?;
match &self.view_id {
Some(s) => write!(f, "viewId={}", s)?,
None => write!(f, "")?,
}
match &self.page_size {
Some(s) => write!(f, "&pageSize={}", s)?,
None => write!(f, "")?,
}
match &self.max_records {
Some(s) => write!(f, "&maxRecords={}", s)?,
None => write!(f, "")?,
}
match &self.page_num {
Some(s) => write!(f, "&pageNum={}", s)?,
None => write!(f, "")?,
}
match &self.sort {
Some(s) => write!(f, "&sort={}", serde_json::to_string(s).unwrap())?,
None => write!(f, "")?,
}
match &self.record_ids {
Some(s) => write!(f, "&recordIds={}", s.join(","))?,
None => write!(f, "")?,
}
match &self.fields {
Some(s) => write!(f, "&fields={}", s.join(","))?,
None => write!(f, "")?,
}
match &self.filter_by_formula {
Some(s) => write!(f, "&filterByFormula={}", s)?,
None => write!(f, "")?,
}
match &self.cell_format {
Some(s) => write!(f, "&cellFormat={}", s),
None => write!(f, ""),
}
}
}
#[derive(Default, Debug)]
pub enum FieldKey {
Name,
#[default]
Id,
}
impl std::fmt::Display for FieldKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
FieldKey::Name => write!(f, "name"),
FieldKey::Id => write!(f, "id"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn get_default_query_parameters() -> QueryParameters {
QueryParameters::default()
}
#[test]
fn test_query_parameters_page_num() {
assert_eq!(get_default_query_parameters().page_num, Some(1));
}
#[test]
fn test_query_parameters_page_size() {
assert_eq!(get_default_query_parameters().page_size, Some(1000));
}
#[test]
fn test_query_parameters_max_recordes() {
assert_eq!(get_default_query_parameters().max_records, Some(100000));
}
#[test]
fn test_query_parameters_set() {
// assert_eq!(get_default_query_parameters().sort.len(), 0);
let mut q = QueryParameters::default();
q.set_page_size(Some(12));
assert_eq!(q.page_size, Some(12));
}
#[test]
fn test_query_parameters_to_param() {
let q = get_default_query_parameters();
let u = format!("{}", q);
assert_eq!(u, "?fieldKey=id&pageSize=1000&maxRecords=100000&pageNum=1")
}
}