baserow_rs/
lib.rs

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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
//! A Rust client for the Baserow API
//!
//! This crate provides a strongly-typed client for interacting with Baserow's REST API.
//! It supports authentication, table operations, file uploads, and more.
//!
//! # Example
//! ```no_run
//! use baserow_rs::{ConfigBuilder, Baserow, BaserowTableOperations, api::client::BaserowClient};
//! use std::collections::HashMap;
//! use serde_json::Value;
//!
//! #[tokio::main]
//! async fn main() {
//!     // Create a configuration
//!     let config = ConfigBuilder::new()
//!         .base_url("https://api.baserow.io")
//!         .api_key("your-api-key")
//!         .build();
//!
//!     // Initialize the client
//!     let baserow = Baserow::with_configuration(config);
//!
//!     // Get a table reference
//!     let table = baserow.table_by_id(1234);
//!
//!     // Create a record
//!     let mut data = HashMap::new();
//!     data.insert("Name".to_string(), Value::String("Test".to_string()));
//!
//!     let result = table.create_one(data, None).await.unwrap();
//!     println!("Created record: {:?}", result);
//! }
//! ```

use std::{error::Error, fs::File};

use tracing::{debug, error, info, instrument, span, Level};

use api::{
    authentication::{LoginRequest, TokenResponse, User},
    client::{BaserowClient, RequestTracing},
};
use error::{FileUploadError, TokenAuthError};
use mapper::TableMapper;
use reqwest::{
    header::AUTHORIZATION,
    multipart::{self, Form},
    Body, Client, StatusCode,
};
use serde::{Deserialize, Serialize};
use tokio_util::codec::{BytesCodec, FramedRead};

pub mod api;

#[macro_use]
extern crate async_trait;

pub mod error;
pub mod filter;
pub mod mapper;

/// Configuration for the Baserow client
///
/// This struct holds all the configuration options needed to connect to a Baserow instance,
/// including authentication credentials and API endpoints.
#[derive(Clone, Debug)]
pub struct Configuration {
    base_url: String,

    email: Option<String>,
    password: Option<String>,
    jwt: Option<String>,

    database_token: Option<String>,
    access_token: Option<String>,
    refresh_token: Option<String>,

    user: Option<User>,
}

/// Builder for creating Configuration instances
///
/// Provides a fluent interface for constructing Configuration objects with the required parameters.
///
/// # Example
/// ```
/// use baserow_rs::ConfigBuilder;
///
/// let config = ConfigBuilder::new()
///     .base_url("https://api.baserow.io")
///     .api_key("your-api-key")
///     .build();
/// ```
#[derive(Default)]
pub struct ConfigBuilder {
    base_url: Option<String>,
    api_key: Option<String>,
    email: Option<String>,
    password: Option<String>,
}

impl ConfigBuilder {
    pub fn new() -> Self {
        Self {
            base_url: None,
            api_key: None,
            email: None,
            password: None,
        }
    }

    pub fn base_url(mut self, base_url: &str) -> Self {
        self.base_url = Some(base_url.to_string());
        self
    }

    pub fn api_key(mut self, api_key: &str) -> Self {
        self.api_key = Some(api_key.to_string());
        self
    }

    pub fn email(mut self, email: &str) -> Self {
        self.email = Some(email.to_string());
        self
    }

    pub fn password(mut self, password: &str) -> Self {
        self.password = Some(password.to_string());
        self
    }

    pub fn build(self) -> Configuration {
        Configuration {
            base_url: self.base_url.unwrap(),

            email: self.email,
            password: self.password,
            jwt: None,

            database_token: self.api_key,
            access_token: None,
            refresh_token: None,

            user: None,
        }
    }
}

/// Main client for interacting with the Baserow API
///
/// This struct implements the BaserowClient trait and provides methods for all API operations.
/// It handles authentication, request signing, and maintains the client state.
#[derive(Clone, Debug)]
pub struct Baserow {
    configuration: Configuration,
    client: Client,
}

impl Baserow {
    pub fn with_configuration(configuration: Configuration) -> Self {
        let span = span!(Level::INFO, "baserow_init");
        let _enter = span.enter();

        info!("Initializing Baserow client with configuration");
        debug!(?configuration, "Configuration details");

        Self {
            configuration,
            client: Client::new(),
        }
    }

    pub fn with_database_token(self, token: String) -> Self {
        let mut configuration = self.configuration.clone();
        configuration.database_token = Some(token);

        Self {
            configuration,
            client: self.client,
        }
    }

    fn with_access_token(&self, access_token: String) -> Self {
        let mut configuration = self.configuration.clone();
        configuration.access_token = Some(access_token);

        Self {
            configuration,
            client: self.client.clone(),
        }
    }

    fn with_refresh_token(&self, refresh_token: String) -> Self {
        let mut configuration = self.configuration.clone();
        configuration.refresh_token = Some(refresh_token);

        Self {
            configuration,
            client: self.client.clone(),
        }
    }

    fn with_user(&self, user: User) -> Self {
        let mut configuration = self.configuration.clone();
        configuration.user = Some(user);

        Self {
            configuration,
            client: self.client.clone(),
        }
    }
}

#[async_trait]
impl BaserowClient for Baserow {
    fn get_configuration(&self) -> Configuration {
        self.configuration.clone()
    }

    fn get_client(&self) -> Client {
        self.client.clone()
    }

    #[instrument(skip(self), err)]
    async fn token_auth(&self) -> Result<Box<dyn BaserowClient>, TokenAuthError> {
        let url = format!("{}/api/user/token-auth/", &self.configuration.base_url);

        let email = self
            .configuration
            .email
            .as_ref()
            .ok_or(TokenAuthError::MissingCredentials("email"))?;

        let password = self
            .configuration
            .password
            .as_ref()
            .ok_or(TokenAuthError::MissingCredentials("password"))?;

        let auth_request = LoginRequest {
            email: email.clone(),
            password: password.clone(),
        };

        let req = Client::new().post(url).json(&auth_request);

        debug!("Sending token authentication request");
        let resp = self.trace_request(&self.client, req.build()?).await?;

        match resp.status() {
            StatusCode::OK => {
                info!("Token authentication successful");
                let token_response: TokenResponse = resp.json().await?;
                let client = self
                    .clone()
                    .with_database_token(token_response.token)
                    .with_access_token(token_response.access_token)
                    .with_refresh_token(token_response.refresh_token)
                    .with_user(token_response.user);
                Ok(Box::new(client) as Box<dyn BaserowClient>)
            }
            _status => {
                let error_text = resp.text().await?;
                let error = TokenAuthError::AuthenticationFailed(error_text);
                error.log();
                Err(error)
            }
        }
    }

    #[instrument(skip(self), err)]
    async fn table_fields(&self, table_id: u64) -> Result<Vec<TableField>, Box<dyn Error>> {
        let url = format!(
            "{}/api/database/fields/table/{}/",
            &self.configuration.base_url, table_id
        );

        let mut req = self.client.get(url);

        if let Some(token) = &self.configuration.jwt {
            req = req.header(AUTHORIZATION, format!("JWT {}", token));
        } else if let Some(token) = &self.configuration.database_token {
            req = req.header(AUTHORIZATION, format!("Token {}", token));
        } else {
            return Err("No authentication token provided".into());
        }

        debug!("Sending request to fetch table fields");
        let resp = self.trace_request(&self.client, req.build()?).await?;
        match resp.status() {
            StatusCode::OK => {
                let fields: Vec<TableField> = resp.json().await?;
                info!(
                    field_count = fields.len(),
                    "Successfully retrieved table fields"
                );
                debug!(?fields, "Retrieved field details");
                Ok(fields)
            }
            status => {
                let error_text = resp.text().await?;
                error!(%status, error = %error_text, "Failed to retrieve table fields");
                Err(format!(
                    "Failed to retrieve table fields (status: {}): {}",
                    status, error_text
                )
                .into())
            }
        }
    }

    fn table_by_id(&self, id: u64) -> BaserowTable {
        BaserowTable::default()
            .with_id(id)
            .with_baserow(self.clone())
    }

    #[instrument(skip(self, file), fields(filename = %filename), err)]
    async fn upload_file(
        &self,
        file: File,
        filename: String,
    ) -> Result<api::file::File, FileUploadError> {
        let url = format!(
            "{}/api/user-files/upload-file/",
            &self.configuration.base_url
        );

        let file = tokio::fs::File::from_std(file);
        let stream = FramedRead::new(file, BytesCodec::new());
        let file_body = Body::wrap_stream(stream);

        let mime_type = mime_guess::from_path(&filename).first_or_octet_stream();

        let file_part = multipart::Part::stream(file_body)
            .file_name(filename)
            .mime_str(mime_type.as_ref())?;

        let form = Form::new().part("file", file_part);

        let mut req = self.client.post(url);

        if let Some(token) = &self.configuration.jwt {
            req = req.header(AUTHORIZATION, format!("JWT {}", token));
        } else if let Some(api_key) = &self.configuration.database_token {
            req = req.header(AUTHORIZATION, format!("Token {}", api_key));
        }

        let resp = self
            .trace_request(&self.client, req.multipart(form).build()?)
            .await;

        match resp {
            Ok(resp) => match resp.status() {
                StatusCode::OK => {
                    let json: api::file::File = resp.json().await?;
                    info!("File upload successful");
                    debug!(?json, "Upload response details");
                    Ok(json)
                }
                status => {
                    let error = FileUploadError::UnexpectedStatusCode(status);
                    error.log();
                    Err(error)
                }
            },
            Err(e) => {
                let error = FileUploadError::UploadError(e);
                error.log();
                Err(error)
            }
        }
    }

    #[instrument(skip(self), err)]
    async fn upload_file_via_url(&self, url: &str) -> Result<api::file::File, FileUploadError> {
        // Validate URL format and scheme
        let file_url = url
            .parse::<reqwest::Url>()
            .map_err(|_| FileUploadError::InvalidURL(url.to_string()))?
            .to_string();

        let upload_request = api::file::UploadFileViaUrlRequest {
            url: file_url.clone(),
        };

        let url = format!(
            "{}/api/user-files/upload-via-url/",
            &self.configuration.base_url
        );

        let mut req = self.client.post(url).json(&upload_request);

        if let Some(token) = &self.configuration.jwt {
            req = req.header(AUTHORIZATION, format!("JWT {}", token));
        } else if let Some(api_key) = &self.configuration.database_token {
            req = req.header(AUTHORIZATION, format!("Token {}", api_key));
        }

        let resp = self.trace_request(&self.client, req.build()?).await;

        match resp {
            Ok(resp) => match resp.status() {
                StatusCode::OK => {
                    let json: api::file::File = resp.json().await?;
                    info!("File upload via URL successful");
                    debug!(?json, "Upload response details");
                    Ok(json)
                }
                status => {
                    let error = FileUploadError::UnexpectedStatusCode(status);
                    error.log();
                    Err(error)
                }
            },
            Err(e) => {
                let error = FileUploadError::UploadError(e);
                error.log();
                Err(error)
            }
        }
    }
}

/// Represents a table in Baserow
///
/// This struct provides methods for interacting with a specific table, including
/// creating, reading, updating and deleting records.
#[derive(Deserialize, Serialize, Default, Clone)]
pub struct BaserowTable {
    #[serde(skip)]
    baserow: Option<Baserow>,

    #[serde(skip)]
    mapper: Option<TableMapper>,

    id: Option<u64>,
    pub name: Option<String>,
    order: Option<i64>,
    database_id: Option<i64>,
}

impl BaserowTable {
    fn with_baserow(mut self, baserow: Baserow) -> BaserowTable {
        self.baserow = Some(baserow);
        self
    }

    fn with_id(mut self, id: u64) -> BaserowTable {
        self.id = Some(id);
        self
    }
}

pub use api::table_operations::BaserowTableOperations;

/// Represents a field in a Baserow table
///
/// Contains metadata about a table column including its type, name, and other attributes.
#[derive(Clone, Deserialize, Serialize, Debug)]
pub struct TableField {
    pub id: u64,
    pub table_id: u64,
    pub name: String,
    pub order: u32,
    pub r#type: String,
    pub primary: bool,
    pub read_only: bool,
    pub description: Option<String>,
}

/// Specifies the sort direction for table queries
///
/// Used when ordering table results to determine ascending or descending order.
#[derive(Clone, Debug)]
pub enum OrderDirection {
    Asc,
    Desc,
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::Value;
    use std::collections::HashMap;

    #[test]
    fn test() {
        let configuration = Configuration {
            base_url: "https://baserow.io".to_string(),
            database_token: Some("123".to_string()),
            email: None,
            password: None,
            jwt: None,
            access_token: None,
            refresh_token: None,
            user: None,
        };
        let baserow = Baserow::with_configuration(configuration);
        let _table = baserow.table_by_id(1234);
    }

    #[tokio::test]
    async fn test_create_record() {
        let mut server = mockito::Server::new_async().await;
        let mock_url = server.url();

        let mock = server
            .mock("POST", "/api/database/rows/table/1234/")
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_header(AUTHORIZATION, format!("Token {}", "123").as_str())
            .with_body(r#"{"id": 1234, "field_1": "test"}"#)
            .create();

        let configuration = Configuration {
            base_url: mock_url,
            database_token: Some("123".to_string()),
            email: None,
            password: None,
            jwt: None,
            access_token: None,
            refresh_token: None,
            user: None,
        };
        let baserow = Baserow::with_configuration(configuration);
        let table = baserow.table_by_id(1234);

        let mut record = HashMap::new();
        record.insert("field_1".to_string(), Value::String("test".to_string()));

        let result = table.create_one(record, None).await;
        assert!(result.is_ok());

        let created_record = result.unwrap();
        assert_eq!(created_record["field_1"], Value::String("test".to_string()));

        mock.assert();
    }

    #[tokio::test]
    async fn test_get_record() {
        let mut server = mockito::Server::new_async().await;
        let mock_url = server.url();

        let mock = server
            .mock("GET", "/api/database/rows/table/1234/5678/")
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_header(AUTHORIZATION, format!("Token {}", "123").as_str())
            .with_body(r#"{"id": 5678, "field_1": "test"}"#)
            .create();

        let configuration = Configuration {
            base_url: mock_url,
            database_token: Some("123".to_string()),
            email: None,
            password: None,
            jwt: None,
            access_token: None,
            refresh_token: None,
            user: None,
        };
        let baserow = Baserow::with_configuration(configuration);
        let table = baserow.table_by_id(1234);

        let result: Result<HashMap<String, Value>, Box<dyn Error>> =
            table.get_one(5678, None).await;
        assert!(result.is_ok());

        let record = result.unwrap();
        assert_eq!(record["id"], Value::Number(5678.into()));
        assert_eq!(record["field_1"], Value::String("test".to_string()));

        mock.assert();
    }

    #[tokio::test]
    async fn test_update_record() {
        let mut server = mockito::Server::new_async().await;
        let mock_url = server.url();

        let mock = server
            .mock("PATCH", "/api/database/rows/table/1234/5678/")
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_header(AUTHORIZATION, format!("Token {}", "123").as_str())
            .with_body(r#"{"id": 5678, "field_1": "updated"}"#)
            .create();

        let configuration = Configuration {
            base_url: mock_url,
            database_token: Some("123".to_string()),
            email: None,
            password: None,
            jwt: None,
            access_token: None,
            refresh_token: None,
            user: None,
        };
        let baserow = Baserow::with_configuration(configuration);
        let table = baserow.table_by_id(1234);

        let mut record = HashMap::new();
        record.insert("field_1".to_string(), Value::String("updated".to_string()));

        let result = table.update(5678, record, None).await;
        assert!(result.is_ok());

        let updated_record = result.unwrap();
        assert_eq!(
            updated_record["field_1"],
            Value::String("updated".to_string())
        );

        mock.assert();
    }

    #[tokio::test]
    async fn test_delete_record() {
        let mut server = mockito::Server::new_async().await;
        let mock_url = server.url();

        let mock = server
            .mock("DELETE", "/api/database/rows/table/1234/5678/")
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_header(AUTHORIZATION, format!("Token {}", "123").as_str())
            .create();

        let configuration = Configuration {
            base_url: mock_url,
            database_token: Some("123".to_string()),
            email: None,
            password: None,
            jwt: None,
            access_token: None,
            refresh_token: None,
            user: None,
        };
        let baserow = Baserow::with_configuration(configuration);
        let table = baserow.table_by_id(1234);

        let result = table.delete(5678).await;
        assert!(result.is_ok());

        mock.assert();
    }

    #[tokio::test]
    async fn test_upload_file_via_url() {
        let mut server = mockito::Server::new_async().await;
        let mock_url = server.url();

        let mock = server
            .mock("POST", "/api/user-files/upload-via-url/")
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_header(AUTHORIZATION, format!("Token {}", "123").as_str())
            .with_body(r#"{
    "url": "https://files.baserow.io/user_files/VXotniBOVm8tbstZkKsMKbj2Qg7KmPvn_39d354a76abe56baaf569ad87d0333f58ee4bf3eed368e3b9dc736fd18b09dfd.png",
    "thumbnails": {
        "tiny": {
            "url": "https://files.baserow.io/media/thumbnails/tiny/VXotniBOVm8tbstZkKsMKbj2Qg7KmPvn_39d354a76abe56baaf569ad87d0333f58ee4bf3eed368e3b9dc736fd18b09dfd.png",
            "width": 21,
            "height": 21
        },
        "small": {
            "url": "https://files.baserow.io/media/thumbnails/small/VXotniBOVm8tbstZkKsMKbj2Qg7KmPvn_39d354a76abe56baaf569ad87d0333f58ee4bf3eed368e3b9dc736fd18b09dfd.png",
            "width": 48,
            "height": 48
        }
    },
    "name": "VXotniBOVm8tbstZkKsMKbj2Qg7KmPvn_39d354a76abe56baaf569ad87d0333f58ee4bf3eed368e3b9dc736fd18b09dfd.png",
    "size": 229940,
    "mime_type": "image/png",
    "is_image": true,
    "image_width": 1280,
    "image_height": 585,
    "uploaded_at": "2020-11-17T12:16:10.035234+00:00"
}"#)
            .create();

        let configuration = Configuration {
            base_url: mock_url,
            database_token: Some("123".to_string()),
            email: None,
            password: None,
            jwt: None,
            access_token: None,
            refresh_token: None,
            user: None,
        };
        let baserow = Baserow::with_configuration(configuration);

        let result = baserow
            .upload_file_via_url("https://example.com/test.txt")
            .await;
        assert!(result.is_ok());

        let uploaded_file = result.unwrap();
        assert_eq!(uploaded_file.name, "VXotniBOVm8tbstZkKsMKbj2Qg7KmPvn_39d354a76abe56baaf569ad87d0333f58ee4bf3eed368e3b9dc736fd18b09dfd.png".to_string());

        mock.assert();
    }

    #[tokio::test]
    async fn test_token_auth() {
        let mut server = mockito::Server::new_async().await;
        let mock_url = server.url();

        let mock = server
            .mock("POST", "/api/user/token-auth/")
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(
                r#"{
  "user": {
    "first_name": "string",
    "username": "user@example.com",
    "language": "string"
  },
  "token": "string",
  "access_token": "string",
  "refresh_token": "string"
}"#,
            )
            .create();

        let configuration = ConfigBuilder::new()
            .base_url(&mock_url)
            .email("test@example.com")
            .password("password")
            .build();
        let baserow = Baserow::with_configuration(configuration);

        let result = baserow.token_auth().await;
        assert!(result.is_ok());

        let logged_in_baserow = result.unwrap();
        assert_eq!(
            logged_in_baserow
                .get_configuration()
                .database_token
                .unwrap(),
            "string"
        );

        mock.assert();
    }

    #[tokio::test]
    async fn test_upload_file() {
        let mut server = mockito::Server::new_async().await;
        let mock_url = server.url();

        let mock = server
            .mock("POST", "/api/user-files/upload-file/")
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_header(AUTHORIZATION, format!("Token {}", "123").as_str())
            .with_body(r#"{
    "url": "https://files.baserow.io/user_files/VXotniBOVm8tbstZkKsMKbj2Qg7KmPvn_39d354a76abe56baaf569ad87d0333f58ee4bf3eed368e3b9dc736fd18b09dfd.png",
    "thumbnails": {
        "tiny": {
            "url": "https://files.baserow.io/media/thumbnails/tiny/VXotniBOVm8tbstZkKsMKbj2Qg7KmPvn_39d354a76abe56baaf569ad87d0333f58ee4bf3eed368e3b9dc736fd18b09dfd.png",
            "width": 21,
            "height": 21
        },
        "small": {
            "url": "https://files.baserow.io/media/thumbnails/small/VXotniBOVm8tbstZkKsMKbj2Qg7KmPvn_39d354a76abe56baaf569ad87d0333f58ee4bf3eed368e3b9dc736fd18b09dfd.png",
            "width": 48,
            "height": 48
        }
    },
    "name": "VXotniBOVm8tbstZkKsMKbj2Qg7KmPvn_39d354a76abe56baaf569ad87d0333f58ee4bf3eed368e3b9dc736fd18b09dfd.png",
    "size": 229940,
    "mime_type": "image/png",
    "is_image": true,
    "image_width": 1280,
    "image_height": 585,
    "uploaded_at": "2020-11-17T12:16:10.035234+00:00"
}"#)
            .create();

        let configuration = Configuration {
            base_url: mock_url,
            database_token: Some("123".to_string()),
            email: None,
            password: None,
            jwt: None,
            access_token: None,
            refresh_token: None,
            user: None,
        };
        let baserow = Baserow::with_configuration(configuration);

        let file = File::open(".gitignore").unwrap();
        let result = baserow.upload_file(file, "image.png".to_string()).await;
        assert!(result.is_ok());

        let uploaded_file = result.unwrap();
        assert_eq!(uploaded_file.name, "VXotniBOVm8tbstZkKsMKbj2Qg7KmPvn_39d354a76abe56baaf569ad87d0333f58ee4bf3eed368e3b9dc736fd18b09dfd.png".to_string());

        mock.assert();
    }

    #[tokio::test]
    async fn test_view_query() {
        let mut server = mockito::Server::new_async().await;
        let mock_url = server.url();

        let mock = server
            .mock("GET", "/api/database/rows/table/1234/")
            .match_query(mockito::Matcher::UrlEncoded("view_id".into(), "5678".into()))
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_header(AUTHORIZATION, format!("Token {}", "123").as_str())
            .with_body(r#"{"count": 1, "next": null, "previous": null, "results": [{"id": 1, "field_1": "test"}]}"#)
            .create();

        let configuration = Configuration {
            base_url: mock_url,
            database_token: Some("123".to_string()),
            email: None,
            password: None,
            jwt: None,
            access_token: None,
            refresh_token: None,
            user: None,
        };
        let baserow = Baserow::with_configuration(configuration);
        let table = baserow.table_by_id(1234);

        let result = table
            .query()
            .view(5678)
            .get::<HashMap<String, Value>>()
            .await;

        assert!(result.is_ok());
        let response = result.unwrap();
        assert_eq!(response.count, Some(1));
        assert_eq!(
            response.results[0]["field_1"],
            Value::String("test".to_string())
        );

        mock.assert();
    }

    #[tokio::test]
    async fn test_view_query_with_filters() {
        let mut server = mockito::Server::new_async().await;
        let mock_url = server.url();

        let mock = server
            .mock("GET", "/api/database/rows/table/1234/")
            .match_query(mockito::Matcher::AllOf(vec![
                mockito::Matcher::UrlEncoded("view_id".into(), "5678".into()),
                mockito::Matcher::UrlEncoded("filter__field_1__equal".into(), "test".into()),
                mockito::Matcher::UrlEncoded("order_by".into(), "field_1".into()),
            ]))
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_header(AUTHORIZATION, format!("Token {}", "123").as_str())
            .with_body(r#"{"count": 1, "next": null, "previous": null, "results": [{"id": 1, "field_1": "test"}]}"#)
            .create();

        let configuration = Configuration {
            base_url: mock_url,
            database_token: Some("123".to_string()),
            email: None,
            password: None,
            jwt: None,
            access_token: None,
            refresh_token: None,
            user: None,
        };
        let baserow = Baserow::with_configuration(configuration);
        let table = baserow.table_by_id(1234);

        let result = table
            .query()
            .view(5678)
            .filter_by("field_1", filter::Filter::Equal, "test")
            .order_by("field_1", OrderDirection::Asc)
            .get::<HashMap<String, Value>>()
            .await;

        assert!(result.is_ok());
        let response = result.unwrap();
        assert_eq!(response.count, Some(1));
        assert_eq!(
            response.results[0]["field_1"],
            Value::String("test".to_string())
        );

        mock.assert();
    }

    #[tokio::test]
    async fn test_view_query_with_pagination() {
        let mut server = mockito::Server::new_async().await;
        let mock_url = server.url();

        let mock = server
            .mock("GET", "/api/database/rows/table/1234/")
            .match_query(mockito::Matcher::AllOf(vec![
                mockito::Matcher::UrlEncoded("view_id".into(), "5678".into()),
                mockito::Matcher::UrlEncoded("size".into(), "2".into()),
                mockito::Matcher::UrlEncoded("page".into(), "1".into()),
            ]))
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_header(AUTHORIZATION, format!("Token {}", "123").as_str())
            .with_body(r#"{"count": 3, "next": "http://example.com/next", "previous": "http://example.com/prev", "results": [{"id": 2, "field_1": "test2"}, {"id": 3, "field_1": "test3"}]}"#)
            .create();

        let configuration = Configuration {
            base_url: mock_url,
            database_token: Some("123".to_string()),
            email: None,
            password: None,
            jwt: None,
            access_token: None,
            refresh_token: None,
            user: None,
        };
        let baserow = Baserow::with_configuration(configuration);
        let table = baserow.table_by_id(1234);

        let result = table
            .query()
            .view(5678)
            .size(2)
            .page(1)
            .get::<HashMap<String, Value>>()
            .await;

        assert!(result.is_ok());
        let response = result.unwrap();
        assert_eq!(response.count, Some(3));
        assert_eq!(response.next, Some("http://example.com/next".to_string()));
        assert_eq!(
            response.previous,
            Some("http://example.com/prev".to_string())
        );
        assert_eq!(response.results.len(), 2);
        assert_eq!(
            response.results[0]["field_1"],
            Value::String("test2".to_string())
        );
        assert_eq!(
            response.results[1]["field_1"],
            Value::String("test3".to_string())
        );

        mock.assert();
    }

    #[tokio::test]
    async fn test_query_with_user_field_names() {
        let mut server = mockito::Server::new_async().await;
        let mock_url = server.url();

        let mock = server
            .mock("GET", "/api/database/rows/table/1234/")
            .match_query(mockito::Matcher::UrlEncoded(
                "user_field_names".into(),
                "true".into(),
            ))
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_header(AUTHORIZATION, format!("Token {}", "123").as_str())
            .with_body(r#"{"count": 1, "next": null, "previous": null, "results": [{"User Name": "test"}]}"#)
            .create();

        let configuration = Configuration {
            base_url: mock_url,
            database_token: Some("123".to_string()),
            email: None,
            password: None,
            jwt: None,
            access_token: None,
            refresh_token: None,
            user: None,
        };
        let baserow = Baserow::with_configuration(configuration);
        let table = baserow.table_by_id(1234);

        let result = table
            .query()
            .user_field_names(true)
            .get::<HashMap<String, Value>>()
            .await;

        assert!(result.is_ok());
        let response = result.unwrap();
        assert_eq!(response.count, Some(1));
        assert_eq!(
            response.results[0]["User Name"],
            Value::String("test".to_string())
        );

        mock.assert();
    }

    #[tokio::test]
    async fn test_view_query_invalid_view() {
        let mut server = mockito::Server::new_async().await;
        let mock_url = server.url();

        let mock = server
            .mock("GET", "/api/database/rows/table/1234/")
            .match_query(mockito::Matcher::UrlEncoded(
                "view_id".into(),
                "9999".into(),
            ))
            .with_status(404)
            .with_header("Content-Type", "application/json")
            .with_header(AUTHORIZATION, format!("Token {}", "123").as_str())
            .with_body(r#"{"error": "View does not exist."}"#)
            .create();

        let configuration = Configuration {
            base_url: mock_url,
            database_token: Some("123".to_string()),
            email: None,
            password: None,
            jwt: None,
            access_token: None,
            refresh_token: None,
            user: None,
        };
        let baserow = Baserow::with_configuration(configuration);
        let table = baserow.table_by_id(1234);

        let result = table
            .query()
            .view(9999)
            .get::<HashMap<String, Value>>()
            .await;

        assert!(result.is_err());
        mock.assert();
    }

    #[tokio::test]
    async fn test_table_fields() {
        let mut server = mockito::Server::new_async().await;
        let mock_url = server.url();

        let mock = server
            .mock("GET", "/api/database/fields/table/1234/")
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_header(AUTHORIZATION, format!("Token {}", "123").as_str())
            .with_body(
                r#"[
    {
        "id": 1529,
        "table_id": 1234,
        "name": "Name",
        "order": 0,
        "type": "text",
        "primary": true,
        "read_only": false,
        "description": "A sample description"
    },
    {
        "id": 6499,
        "table_id": 1234,
        "name": "Field 2",
        "order": 1,
        "type": "last_modified",
        "primary": false,
        "read_only": true,
        "description": "A sample description"
    },
    {
        "id": 6500,
        "table_id": 1234,
        "name": "Datei",
        "order": 2,
        "type": "file",
        "primary": false,
        "read_only": false,
        "description": "A sample description"
    }
]"#,
            )
            .create();

        let configuration = Configuration {
            base_url: mock_url,
            database_token: Some("123".to_string()),
            email: None,
            password: None,
            jwt: None,
            access_token: None,
            refresh_token: None,
            user: None,
        };
        let baserow = Baserow::with_configuration(configuration);

        let result = baserow.table_fields(1234).await;

        print!("result: {:#?}", result);

        assert!(result.is_ok());

        let fields = result.unwrap();
        assert_eq!(fields.len(), 3);
        assert_eq!(fields[0].id, 1529);
        assert_eq!(fields[0].table_id, 1234);
        assert_eq!(fields[0].name, "Name");
        assert_eq!(fields[1].id, 6499);
        assert_eq!(fields[1].table_id, 1234);
        assert_eq!(fields[1].name, "Field 2");

        mock.assert();
    }
}