any_type 0.5.0

A library for the Anytype API
Documentation
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
use crate::api::RequestFailure;
use crate::icons::Icon;
use crate::node;
use crate::properties::{Property, PropertyFormat};
use crate::types::{Type, TypeLayout};
use serde_json::{Map, Number, Value};

async fn response_to_object(response: reqwest::Response) -> Object {
    let json_input = response.text().await.unwrap();
    let json: serde_json::Value = serde_json::from_str(json_input.as_ref()).unwrap();
    let o = json["object"].clone();
    json_to_object(o)
}

pub(crate) async fn response_to_list(response: reqwest::Response) -> ListOfObjects {
    let json_input = response.text().await.unwrap();
    let json: serde_json::Value = serde_json::from_str(json_input.as_ref()).unwrap();
    let received = json["data"].as_array().unwrap();
    let mut data: Vec<Object> = Vec::new();
    for o in 0..received.len() {
        let obj = json_to_object(received[o].clone());
        data.push(obj);
    }
    let has_more: bool = json["pagination"]["has_more"].as_bool().unwrap();
    let total = json["pagination"]["total"].as_u64().unwrap() as usize;
    let offset = json["pagination"]["offset"].as_u64().unwrap() as usize;
    let limit = json["pagination"]["limit"].as_u64().unwrap() as usize;
    let next_offset = (offset as usize) + received.len();

    ListOfObjects {
        objects: data,
        has_more,
        next_offset,
        offset,
        limit,
        total,
    }
}

fn json_to_object(json: Value) -> Object {
    let id = json["id"].as_str().unwrap().to_string();
    let archived = json["archived"].as_bool().unwrap();
    let icon = Icon::from_json(json["icon"].clone());
    let json_properties = json["properties"].as_array().unwrap();
    let mut properties: Vec<Property> = Vec::new();
    for p in 0..json_properties.len() {
        let format = json_properties[p]["format"].as_str().unwrap().to_string();
        let key = json_properties[p]["key"].as_str().unwrap().to_string();
        let name = json_properties[p]["name"].as_str().unwrap().to_string();
        let id = json_properties[p]["id"].as_str().unwrap().to_string();
        let object = match json_properties[p]["object"].as_str() {
            Some(s) => s.to_string(),
            None => "".to_string(),
        };
        properties.push(Property {
            format: PropertyFormat::from_str(&format),
            key,
            name,
            id,
            object,
        });
    }
    let layout = json["layout"].as_str().unwrap().to_string();
    let markdown: String = match json["markdown"].as_str() {
        Some(m) => m.to_string(),
        None => "".to_string(),
    };
    let name = json["name"].as_str().unwrap().to_string();
    let object = json["object"].as_str().unwrap().to_string();
    let snippet = json["snippet"].as_str().unwrap().to_string();
    let space_id = json["space_id"].as_str().unwrap().to_string();
    let type_obj = match json["type"]["id"].as_str() {
        Some(_) => Some(Type::from_json(json["type"].clone())),
        None => None,
    };
    Object {
        archived,
        icon,
        id,
        layout: TypeLayout::from_str(&layout),
        markdown,
        name,
        object,
        properties,
        snippet,
        space_id,
        type_obj,
    }
}

#[derive(Debug)]
pub struct Object {
    pub archived: bool,
    pub icon: Option<Icon>,
    pub id: String,
    pub layout: TypeLayout,
    pub markdown: String,
    pub name: String,
    pub object: String,
    pub properties: Vec<Property>,
    pub snippet: String,
    pub space_id: String,
    pub type_obj: Option<Type>,
}
impl Object {
    pub fn from_json(json: Value) -> Self {
        let id = json["id"].as_str().unwrap().to_string();
        let archived = json["archived"].as_bool().unwrap();
        let icon = Icon::from_json(json["icon"].clone());
        let json_properties = json["properties"].as_array().unwrap();
        let mut properties: Vec<Property> = Vec::new();
        for p in 0..json_properties.len() {
            properties.push(Property::from_json(json_properties[p].clone()));
        }
        let layout = json["layout"].as_str().unwrap().to_string();
        let markdown: String = match json["markdown"].as_str() {
            Some(m) => m.to_string(),
            None => "".to_string(),
        };
        let name = json["name"].as_str().unwrap().to_string();
        let object = json["object"].as_str().unwrap().to_string();
        let snippet = json["snippet"].as_str().unwrap().to_string();
        let space_id = json["space_id"].as_str().unwrap().to_string();
        let type_obj = match json["type"]["id"].as_str() {
            Some(_) => Some(Type::from_json(json["type"].clone())),
            None => None,
        };
        Object {
            archived,
            icon,
            id,
            layout: TypeLayout::from_str(&layout),
            markdown,
            name,
            object,
            properties,
            snippet,
            space_id,
            type_obj,
        }
    }
}

#[derive(Debug)]
pub struct ListOfObjects {
    pub objects: Vec<Object>,
    pub has_more: bool,
    pub next_offset: usize,
    pub offset: usize,
    pub limit: usize,
    pub total: usize,
}

#[derive(Debug)]
pub struct ListObjectsRequest<'a> {
    api_key: &'a str,
    offset: u32,
    limit: u32,
    server: &'a str,
    space_id: &'a str,
}
impl<'a> ListObjectsRequest<'a> {
    pub fn new(api_key: &'a str, server: &'a str) -> Self {
        ListObjectsRequest {
            api_key,
            offset: 0,
            limit: 100,
            server,
            space_id: "",
        }
    }
    pub fn space_id(mut self, space_id: &'a str) -> Self {
        self.space_id = space_id;
        self
    }
    pub fn offset(mut self, offset: u32) -> Self {
        self.offset = offset;
        self
    }
    pub fn limit(mut self, limit: u32) -> Self {
        self.limit = limit;
        self
    }
    pub async fn send(&self) -> Result<ListOfObjects, RequestFailure> {
        let endpoint = format!("/v1/spaces/{}/objects", self.space_id);
        match node::get(self.api_key, self.server, &endpoint).await {
            Ok(r) => Ok(response_to_list(r).await),
            Err(e) => Err(RequestFailure::reqwest_error(e)),
        }
    }
}

#[derive(Debug)]
pub struct CreateObjectRequest<'a> {
    api_key: &'a str,
    body: Value,
    icon: Value,
    name: Value,
    properties: Vec<Value>,
    server: &'a str,
    space_id: &'a str,
    template_id: Value,
    type_key: Value,
}
impl<'a> CreateObjectRequest<'a> {
    pub fn new(api_key: &'a str, server: &'a str) -> Self {
        CreateObjectRequest {
            api_key,
            body: Value::String("".to_string()),
            icon: Value::Null,
            name: Value::String("".to_string()),
            properties: Vec::new(),
            server,
            space_id: "",
            template_id: Value::String("".to_string()),
            type_key: Value::String("".to_string()),
        }
    }
    pub fn space_id(mut self, space_id: &'a str) -> Self {
        self.space_id = space_id;
        self
    }
    pub fn body(mut self, body: &str) -> Self {
        self.body = Value::String(body.to_string());
        self
    }
    pub fn name(mut self, name: &str) -> Self {
        self.name = Value::String(name.to_string());
        self
    }
    pub fn icon(mut self, icon: &Icon) -> Self {
        self.icon = icon.to_json();
        self
    }
    pub fn template_id(mut self, template_id: &str) -> Self {
        self.template_id = Value::String(template_id.to_string());
        self
    }
    pub fn type_key(mut self, type_key: &str) -> Self {
        self.type_key = Value::String(type_key.to_string());
        self
    }
    pub fn property(mut self, ptype: PropertyFormat, pkey: &str, pvalue: &str) -> Self {
        let mut values = Map::new();
        values.insert("key".to_string(), Value::String(pkey.to_string()));
        match ptype {
            PropertyFormat::Checkbox => {
                if pvalue.to_ascii_lowercase() == "true" {
                    values.insert("checkbox".to_string(), Value::Bool(true));
                } else {
                    values.insert("checkbox".to_string(), Value::Bool(false));
                }
            }
            PropertyFormat::Date => {
                values.insert("date".to_string(), Value::String(pvalue.to_string()));
            }
            PropertyFormat::Email => {
                values.insert("email".to_string(), Value::String(pvalue.to_string()));
            }
            PropertyFormat::Files => {
                let mut files: Vec<Value> = Vec::new();
                files.push(Value::String(pvalue.to_string()));
                values.insert("files".to_string(), Value::Array(files));
            }
            PropertyFormat::Number => {
                let num: Number = match pvalue.parse::<i128>() {
                    Ok(num) => Number::from_i128(num).unwrap(),
                    Err(_) => Number::from_i128(-1).unwrap(),
                };
                values.insert("number".to_string(), Value::Number(num));
            }
            PropertyFormat::MultiSelect => {
                values.insert(
                    "multi_select".to_string(),
                    Value::String(pvalue.to_string()),
                );
            }
            PropertyFormat::Objects => {
                let mut objects: Vec<Value> = Vec::new();
                objects.push(Value::String(pvalue.to_string()));
                values.insert("objects".to_string(), Value::Array(objects));
            }
            PropertyFormat::Phone => {
                values.insert("phone".to_string(), Value::String(pvalue.to_string()));
            }
            PropertyFormat::Select => {
                values.insert("select".to_string(), Value::String(pvalue.to_string()));
            }
            PropertyFormat::Text => {
                values.insert("text".to_string(), Value::String(pvalue.to_string()));
            }
            PropertyFormat::Url => {
                values.insert("url".to_string(), Value::String(pvalue.to_string()));
            }
        }
        self.properties.push(Value::Object(values));
        self
    }
    fn to_string(&self) -> String {
        let mut values = Map::new();
        values.insert("icon".to_string(), self.icon.clone());
        values.insert("body".to_string(), self.body.clone());
        values.insert("name".to_string(), self.name.clone());
        values.insert("template_id".to_string(), self.template_id.clone());
        values.insert("type_key".to_string(), self.type_key.clone());
        let mut properties: Vec<Value> = Vec::new();
        for p in self.properties.iter() {
            properties.push(p.clone());
        }
        values.insert("properties".to_string(), Value::Array(properties));
        Value::Object(values).to_string()
    }

    pub async fn send(&self) -> Result<Object, RequestFailure> {
        let endpoint = format!("/v1/spaces/{}/objects", self.space_id);
        println!("{}", self.to_string());
        let body = self.to_string();
        match node::post(self.api_key, self.server, &endpoint, &body).await {
            Ok(response) => {
                if response.status() == http::StatusCode::CREATED {
                    return Ok(response_to_object(response).await);
                } else {
                    let possible_status: Vec<http::StatusCode> = Vec::from([
                        http::StatusCode::UNAUTHORIZED,
                        http::StatusCode::BAD_REQUEST,
                        http::StatusCode::TOO_MANY_REQUESTS,
                        http::StatusCode::INTERNAL_SERVER_ERROR,
                    ]);
                    return Err(RequestFailure::api_error(response, possible_status).await);
                }
            }
            Err(e) => Err(RequestFailure::reqwest_error(e)),
        }
    }
}

#[derive(Debug)]
pub struct DeleteObjectRequest<'a> {
    api_key: &'a str,
    server: &'a str,
    space_id: &'a str,
    object_id: &'a str,
}
impl<'a> DeleteObjectRequest<'a> {
    pub fn new(api_key: &'a str, server: &'a str) -> Self {
        DeleteObjectRequest {
            api_key,
            server,
            space_id: "",
            object_id: "",
        }
    }
    pub fn space_id(mut self, space_id: &'a str) -> Self {
        self.space_id = space_id;
        self
    }
    pub fn object_id(mut self, object_id: &'a str) -> Self {
        self.object_id = object_id;
        self
    }

    pub async fn send(&self) -> Result<Object, RequestFailure> {
        let endpoint = format!("/v1/spaces/{}/objects/{}", self.space_id, self.object_id);
        match node::delete(self.api_key, self.server, &endpoint).await {
            Ok(response) => {
                if response.status() == http::StatusCode::OK {
                    return Ok(response_to_object(response).await);
                } else {
                    let possible_status: Vec<http::StatusCode> = Vec::from([
                        http::StatusCode::UNAUTHORIZED,
                        http::StatusCode::NOT_FOUND,
                        http::StatusCode::GONE,
                        http::StatusCode::INTERNAL_SERVER_ERROR,
                    ]);
                    return Err(RequestFailure::api_error(response, possible_status).await);
                }
            }
            Err(e) => Err(RequestFailure::reqwest_error(e)),
        }
    }
}

#[derive(Debug)]
pub struct GetObjectRequest<'a> {
    api_key: &'a str,
    server: &'a str,
    space_id: &'a str,
    object_id: &'a str,
}
impl<'a> GetObjectRequest<'a> {
    pub fn new(api_key: &'a str, server: &'a str) -> Self {
        GetObjectRequest {
            api_key,
            server,
            space_id: "",
            object_id: "",
        }
    }
    pub fn space_id(mut self, space_id: &'a str) -> Self {
        self.space_id = space_id;
        self
    }
    pub fn object_id(mut self, object_id: &'a str) -> Self {
        self.object_id = object_id;
        self
    }

    pub async fn send(&self) -> Result<Object, RequestFailure> {
        let endpoint = format!("/v1/spaces/{}/objects/{}", self.space_id, self.object_id);
        match node::get(self.api_key, self.server, &endpoint).await {
            Ok(response) => {
                if response.status() == http::StatusCode::OK {
                    return Ok(response_to_object(response).await);
                } else {
                    let possible_status: Vec<http::StatusCode> = Vec::from([
                        http::StatusCode::UNAUTHORIZED,
                        http::StatusCode::NOT_FOUND,
                        http::StatusCode::GONE,
                        http::StatusCode::INTERNAL_SERVER_ERROR,
                    ]);
                    return Err(RequestFailure::api_error(response, possible_status).await);
                }
            }
            Err(e) => Err(RequestFailure::reqwest_error(e)),
        }
    }
}
#[derive(Debug)]
pub struct UpdateObjectRequest<'a> {
    api_key: &'a str,
    icon: Value,
    markdown: Value,
    name: Value,
    object_id: &'a str,
    properties: Vec<Value>,
    server: &'a str,
    space_id: &'a str,
    type_key: Value,
}
impl<'a> UpdateObjectRequest<'a> {
    pub fn new(api_key: &'a str, server: &'a str) -> Self {
        UpdateObjectRequest {
            api_key,
            icon: Value::Null,
            markdown: Value::String("".to_string()),
            name: Value::String("".to_string()),
            object_id: "",
            properties: Vec::new(),
            server,
            space_id: "",
            type_key: Value::String("".to_string()),
        }
    }
    pub fn space_id(mut self, space_id: &'a str) -> Self {
        self.space_id = space_id;
        self
    }
    pub fn object_id(mut self, object_id: &'a str) -> Self {
        self.object_id = object_id;
        self
    }
    pub fn markdown(mut self, markdown: &str) -> Self {
        self.markdown = Value::String(markdown.to_string());
        self
    }
    pub fn name(mut self, name: &str) -> Self {
        self.name = Value::String(name.to_string());
        self
    }
    pub fn icon(mut self, icon: &Icon) -> Self {
        self.icon = icon.to_json();
        self
    }
    pub fn type_key(mut self, type_key: &str) -> Self {
        self.type_key = Value::String(type_key.to_string());
        self
    }
    pub fn property(mut self, ptype: PropertyFormat, pkey: &str, pvalue: &str) -> Self {
        let mut values = Map::new();
        values.insert("key".to_string(), Value::String(pkey.to_string()));
        match ptype {
            PropertyFormat::Checkbox => {
                if pvalue.to_ascii_lowercase() == "true" {
                    values.insert("checkbox".to_string(), Value::Bool(true));
                } else {
                    values.insert("checkbox".to_string(), Value::Bool(false));
                }
            }
            PropertyFormat::Date => {
                values.insert("date".to_string(), Value::String(pvalue.to_string()));
            }
            PropertyFormat::Email => {
                values.insert("email".to_string(), Value::String(pvalue.to_string()));
            }
            PropertyFormat::Files => {
                let mut files: Vec<Value> = Vec::new();
                files.push(Value::String(pvalue.to_string()));
                values.insert("files".to_string(), Value::Array(files));
            }
            PropertyFormat::Number => {
                let num: Number = match pvalue.parse::<i128>() {
                    Ok(num) => Number::from_i128(num).unwrap(),
                    Err(_) => Number::from_i128(-1).unwrap(),
                };
                values.insert("number".to_string(), Value::Number(num));
            }
            PropertyFormat::MultiSelect => {
                values.insert(
                    "multi_select".to_string(),
                    Value::String(pvalue.to_string()),
                );
            }
            PropertyFormat::Objects => {
                let mut objects: Vec<Value> = Vec::new();
                objects.push(Value::String(pvalue.to_string()));
                values.insert("objects".to_string(), Value::Array(objects));
            }
            PropertyFormat::Phone => {
                values.insert("phone".to_string(), Value::String(pvalue.to_string()));
            }
            PropertyFormat::Select => {
                values.insert("select".to_string(), Value::String(pvalue.to_string()));
            }
            PropertyFormat::Text => {
                values.insert("text".to_string(), Value::String(pvalue.to_string()));
            }
            PropertyFormat::Url => {
                values.insert("url".to_string(), Value::String(pvalue.to_string()));
            }
        }
        self.properties.push(Value::Object(values));
        self
    }
    fn to_string(&self) -> String {
        let mut values = Map::new();
        values.insert("icon".to_string(), self.icon.clone());
        values.insert("markdown".to_string(), self.markdown.clone());
        values.insert("name".to_string(), self.name.clone());
        values.insert("type_key".to_string(), self.type_key.clone());
        let mut properties: Vec<Value> = Vec::new();
        for p in self.properties.iter() {
            properties.push(p.clone());
        }
        values.insert("properties".to_string(), Value::Array(properties));
        Value::Object(values).to_string()
    }

    pub async fn send(&self) -> Result<Object, RequestFailure> {
        let endpoint = format!("/v1/spaces/{}/objects/{}", self.space_id, self.object_id);
        println!("{}", self.to_string());
        let body = self.to_string();
        match node::patch(self.api_key, self.server, &endpoint, &body).await {
            Ok(response) => {
                if response.status() == http::StatusCode::CREATED {
                    return Ok(response_to_object(response).await);
                } else {
                    let possible_status: Vec<http::StatusCode> = Vec::from([
                        http::StatusCode::UNAUTHORIZED,
                        http::StatusCode::BAD_REQUEST,
                        http::StatusCode::TOO_MANY_REQUESTS,
                        http::StatusCode::INTERNAL_SERVER_ERROR,
                    ]);
                    return Err(RequestFailure::api_error(response, possible_status).await);
                }
            }
            Err(e) => Err(RequestFailure::reqwest_error(e)),
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    #[test]
    pub fn test_create_object_request() {
        let request = CreateObjectRequest::new("secret_api_key", "server_url")
            .name("name_of_object")
            .body("body_of_object")
            .template_id("id_of_template")
            .property(PropertyFormat::Checkbox, "completed", "true")
            .property(PropertyFormat::Files, "attached", "bringyourownfiles")
            .property(
                PropertyFormat::Objects,
                "things_to_have",
                "bringyourownobjects",
            )
            .body("I changed my mind, here is the text!")
            .type_key("test_object");
        let internals = format!("{:#?}", request);
        assert!(internals.contains("api_key: \"secret_api_key"));
        assert!(internals.contains("server: \"server_url"));
        println!("{}", internals);
    }

    #[test]
    pub fn test_list_objects_request() {
        let request = ListObjectsRequest::new("secret_api_key", "server_url")
            .space_id("lost_in_space")
            .offset(0)
            .limit(42);
        let internals = format!("{:#?}", request);
        assert!(internals.contains("api_key: \"secret_api_key"));
        assert!(internals.contains("offset: 0"));
        assert!(internals.contains("limit: 42"));
        assert!(internals.contains("space_id: \"lost_in_space"));
        assert!(internals.contains("server: \"server_url"));
        println!("{}", internals);
    }
}