unofficial_appwrite 1.0.0

wrapper on appwrite api -> https://appwrite.io/docs
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
use serde_json::{Map, Value};
///! # Teams
///! The Teams service allows you to group users of your project and to enable
///! them to share read and write access to your project resources
use std::collections::HashMap;

use crate::{
    app_json_header,
    client::Client,
    enumm::HttpMethod,
    error::Error,
    models::{
        membership::Membership, membership_list::MembershipList, preferences::Preferences,
        team::Team, team_list::TeamList,
    },
};

pub struct Teams;

impl Teams {
    /// List teams
    ///
    /// Get a list of all the teams in which the current user is a member. You can
    /// use the parameters to filter your results.
    ///* queries => vec(string)?
    ///* search => string?
    pub async fn list(client: &Client, args: HashMap<String, Value>) -> Result<TeamList, Error> {
        //const API_PATH: &str = "/functions";
        let api_path = "/teams";

        let api_headers = app_json_header!();

        let res = client
            .call(HttpMethod::GET, api_path, api_headers, &args, None)
            .await?;

        Ok(res.json().await?)
    }

    /// Create team
    ///
    /// Create a new team. The user who creates the team will automatically be
    /// assigned as the owner of the team. Only the users with the owner role can
    /// invite new members, add new owners and delete or update the team.
    ///* teamId => string
    ///* name => string
    ///* roles => vec(string)?
    pub async fn create(client: &Client, args: HashMap<String, Value>) -> Result<Team, Error> {
        //const API_PATH: &str = "/functions";
        let api_path = "/teams";

        let api_headers = app_json_header!();

        let res = client
            .call(HttpMethod::POST, api_path, api_headers, &args, None)
            .await?;

        Ok(res.json().await?)
    }

    /// Get team
    ///
    /// Get a team by its ID. All team members have read access for this resource.
    pub async fn get(client: &Client, team_id: &str) -> Result<Team, Error> {
        //const API_PATH: &str = "/functions";
        let api_path = "/teams/{teamId}".replace("{teamId}", team_id);

        let args = HashMap::new();

        let api_headers = app_json_header!();

        let res = client
            .call(HttpMethod::GET, api_path.as_str(), api_headers, &args, None)
            .await?;

        Ok(res.json().await?)
    }

    /// Update name
    ///
    /// Update the team"s name by its unique ID.
    ///* name => string
    pub async fn update_name(
        client: &Client,
        team_id: &str,
        args: HashMap<String, Value>,
    ) -> Result<Team, Error> {
        //const API_PATH: &str = "/functions";
        let api_path = "/teams/{teamId}".replace("{teamId}", team_id);

        let api_headers = app_json_header!();

        let res = client
            .call(HttpMethod::PUT, api_path.as_str(), api_headers, &args, None)
            .await?;

        Ok(res.json().await?)
    }

    /// Delete team
    ///
    /// Delete a team using its ID. Only team members with the owner role can
    /// delete the team.
    pub async fn delete(client: &Client, team_id: &str) -> Result<(), Error> {
        //const API_PATH: &str = "/functions";
        let api_path = "/teams/{teamId}".replace("{teamId}", team_id);

        let args = HashMap::new();

        let api_headers = app_json_header!();

        let _res = client
            .call(
                HttpMethod::DELETE,
                api_path.as_str(),
                api_headers,
                &args,
                None,
            )
            .await?;

        Ok(())
    }

    /// List team memberships
    ///
    /// Use this endpoint to list a team"s members using the team"s ID. All team
    /// members have read access to this endpoint.
    ///* queries => vec(string)?
    ///* search => string?
    pub async fn list_memberships(
        client: &Client,
        team_id: &str,
        args: HashMap<String, Value>,
    ) -> Result<MembershipList, Error> {
        //const API_PATH: &str = "/functions";
        let api_path = "/teams/{teamId}/memberships".replace("{teamId}", team_id);

        let api_headers = app_json_header!();

        let res = client
            .call(HttpMethod::GET, api_path.as_str(), api_headers, &args, None)
            .await?;

        Ok(res.json().await?)
    }

    /// Create team membership
    ///
    /// Invite a new member to join your team. Provide an ID for existing users, or
    /// invite unregistered users using an email or phone number. If initiated from
    /// a Client SDK, Appwrite will send an email or sms with a link to join the
    /// team to the invited user, and an account will be created for them if one
    /// doesn"t exist. If initiated from a Server SDK, the new member will be added
    /// automatically to the team.
    ///
    /// You only need to provide one of a user ID, email, or phone number. Appwrite
    /// will prioritize accepting the user ID > email > phone number if you provide
    /// more than one of these parameters.
    ///
    /// Use the `url` parameter to redirect the user from the invitation email to
    /// your app. After the user is redirected, use the [Update Team Membership
    /// Status](https://appwrite.io/docs/references/cloud/client-web/teams#updateMembershipStatus)
    /// endpoint to allow the user to accept the invitation to the team.
    ///
    /// Please note that to avoid a [Redirect
    /// Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md)
    /// Appwrite will accept the only redirect URLs under the domains you have
    /// added as a platform on the Appwrite Console.
    ///
    ///* roles => vec(string)
    ///* email => string?
    ///* userId => string?
    ///* phone => string?
    ///* url => string?
    ///* name => string?
    pub async fn create_memberships(
        client: &Client,
        team_id: &str,
        args: HashMap<String, Value>,
    ) -> Result<Membership, Error> {
        //const API_PATH: &str = "/functions";
        let api_path = "/teams/{teamId}/memberships".replace("{teamId}", team_id);

        let api_headers = app_json_header!();

        let res = client
            .call(
                HttpMethod::POST,
                api_path.as_str(),
                api_headers,
                &args,
                None,
            )
            .await?;

        Ok(res.json().await?)
    }

    /// Get team membership
    ///
    /// Get a team member by the membership unique id. All team members have read
    /// access for this resource.
    pub async fn get_memberships(
        client: &Client,
        team_id: &str,
        membership_id: &str,
    ) -> Result<Membership, Error> {
        //const API_PATH: &str = "/functions";
        let api_path = "/teams/{teamId}/memberships/{membershipId}"
            .replace("{teamId}", team_id)
            .replace("{membershipId}", membership_id);

        let args = HashMap::new();

        let api_headers = app_json_header!();

        let res = client
            .call(HttpMethod::GET, api_path.as_str(), api_headers, &args, None)
            .await?;

        Ok(res.json().await?)
    }

    /// Update membership
    ///
    /// Modify the roles of a team member. Only team members with the owner role
    /// have access to this endpoint. Learn more about [roles and
    /// permissions](https://appwrite.io/docs/permissions).
    ///
    ///* userId => vec(string)
    pub async fn update_memberships(
        client: &Client,
        team_id: &str,
        membership_id: &str,
        args: HashMap<String, Value>,
    ) -> Result<Membership, Error> {
        //const API_PATH: &str = "/functions";
        let api_path = "/teams/{teamId}/memberships/{membershipId}"
            .replace("{teamId}", team_id)
            .replace("{membershipId}", membership_id);

        let api_headers = app_json_header!();

        let res = client
            .call(
                HttpMethod::PATCH,
                api_path.as_str(),
                api_headers,
                &args,
                None,
            )
            .await?;

        Ok(res.json().await?)
    }

    /// Delete team membership
    ///
    /// This endpoint allows a user to leave a team or for a team owner to delete
    /// the membership of any other team member. You can also use this endpoint to
    /// delete a user membership even if it is not accepted.
    pub async fn delete_memberships(
        client: &Client,
        team_id: &str,
        membership_id: &str,
    ) -> Result<(), Error> {
        //const API_PATH: &str = "/functions";
        let api_path = "/teams/{teamId}/memberships/{membershipId}"
            .replace("{teamId}", team_id)
            .replace("{membershipId}", membership_id);

        let args = HashMap::new();

        let api_headers = app_json_header!();

        let _res = client
            .call(
                HttpMethod::DELETE,
                api_path.as_str(),
                api_headers,
                &args,
                None,
            )
            .await?;

        Ok(())
    }

    /// Update team membership status
    ///
    /// Use this endpoint to allow a user to accept an invitation to join a team
    /// after being redirected back to your app from the invitation email received
    /// by the user.
    ///
    /// If the request is successful, a session for the user is automatically
    /// created.
    ///
    ///* userId => string
    ///* secret => string
    pub async fn update_membership_status(
        client: &Client,
        team_id: &str,
        membership_id: &str,
        args: HashMap<String, Value>,
    ) -> Result<Membership, Error> {
        //const API_PATH: &str = "/functions";
        let api_path = "/teams/{teamId}/memberships/{membershipId}/status"
            .replace("{teamId}", team_id)
            .replace("{membershipId}", membership_id);

        let api_headers = app_json_header!();

        let res = client
            .call(
                HttpMethod::PATCH,
                api_path.as_str(),
                api_headers,
                &args,
                None,
            )
            .await?;

        Ok(res.json().await?)
    }

    /// Get team preferences
    ///
    /// Get the team's shared preferences by its unique ID. If a preference doesn't
    /// need to be shared by all team members, prefer storing them in [user
    /// preferences](https://appwrite.io/docs/references/cloud/client-web/account#getPrefs).
    pub async fn get_prefs(client: &Client, team_id: &str) -> Result<Preferences, Error> {
        //const API_PATH: &str = "/functions";
        let api_path = "/teams/{teamId}/prefs".replace("{teamId}", team_id);

        let args = HashMap::new();

        let api_headers = app_json_header!();

        let res = client
            .call(HttpMethod::GET, api_path.as_str(), api_headers, &args, None)
            .await?;

        Ok(res.json().await?)
    }

    /// Update preferences
    ///
    /// Update the team's preferences by its unique ID. The object you pass is
    /// stored as is and replaces any previous value. The maximum allowed prefs
    /// size is 64kB and throws an error if exceeded.
    ///* prefs => HashMap<String, Value>
    pub async fn update_prefs(
        client: &Client,
        team_id: &str,
        args: HashMap<String, Value>,
    ) -> Result<Preferences, Error> {
        //const API_PATH: &str = "/functions";
        let api_path = "/teams/{teamId}/prefs".replace("{teamId}", team_id);

        let api_headers = app_json_header!();

        let res = client
            .call(HttpMethod::PUT, api_path.as_str(), api_headers, &args, None)
            .await?;

        Ok(res.json().await?)
    }
}

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

    use serde_json::{json, Map, Value};

    use crate::{
        client::ClientBuilder, error::Error, id::ID, query::Query, role::Role,
        services::server::users::Users,
    };

    use super::Teams;

    // #[tokio::test]
    async fn test_teams() -> Result<(), Error> {
        let client = ClientBuilder::default()
            .set_endpoint("http://127.0.0.1/v1")?
            .set_project("676c2b7b000c834e1fce")?
            .set_key("standard_5d84014ebaf0de52308eff28946a43062921240c10b81c2fd037ab60b02f0257b7f0a53fe94065170fe7c7d0af2d4136d4cbf32a4055baeada3d27f2e323b70aeda87e97f676207cf10cbb18b7a80f8d1103803617454c89138f217dad701bbe9dc6950bc58853fdb2a0b4b67d2a8b8b6b7b9b2e6d9b94e0a2fcfee794688e2e")?
            //.set_self_signed(false)?
            .build()?;

        // ! create user
        let create_user1 = Users::create(
            &client,
            maplit::hashmap! {
                "userId".into() => ID::unique(7).into(),
                "email".into()=> "fakeEmailTeams1@Email.com".into(),
                "password".into()=> "VeryVerySecurePassword@123456789".into(),
                "name".into()=> "fakeEmail11".into()
            },
        )
        .await?;
        assert_eq!(create_user1.email.clone(), "fakeemailteams1@email.com");

        let create_user2 = Users::create(
            &client,
            maplit::hashmap! {
                "userId".into() => ID::unique(7).into(),
                "email".into()=> "fakeEmailTeams2@Email.com".into(),
                "password".into()=> "VeryVerySecurePassword@123456789".into(),
                "name".into()=> "fakeEmail22".into()
            },
        )
        .await?;
        assert_eq!(create_user2.email, "fakeemailteams2@email.com");

        // ! create team
        let create_team = Teams::create(
            &client,
            maplit::hashmap! {
                "teamId".into() => ID::unique(7).into(),
                "name".into()=> "boston org".into(),
                "roles".into()=> vec!["maths".to_string(), "geography".to_string(),"english".to_string()].into()
            },
        )
        .await?;
        assert_eq!(create_team.clone().name, "boston org");

        // ! create members
        let users = [create_user1.clone(), create_user2.clone()];
        let mut membership_ids: [String; 2] = [String::new(), String::new()];
        for user in users {
            let roles: Vec<String> = if create_user1.email == "fakeemailteams1@email.com" {
                vec!["maths".to_string(), "geography".to_string()]
            } else {
                vec!["maths".to_string()]
            };
            let create_members = Teams::create_memberships(
                &client,
                &create_team.id,
                maplit::hashmap! {
                    "roles".into()=> roles.into(),
                    "userId".into() => user.id.clone().into(),
                    "email".into()=> user.email.clone().into(),
                    "name".into()=> user.name.clone().into(),
                },
            )
            .await?;
            if create_user1.email == "fakeemailteams1@email.com" {
                membership_ids[0] = create_members.id;
            } else {
                membership_ids[1] = create_members.id;
            };
            assert_eq!(create_members.user_email, user.email);
            assert_eq!(create_members.user_name, user.name);
            assert_eq!(create_members.user_id, user.id);
        }

        // ! update team preference
        let prefs_val: HashMap<String, Value> = maplit::hashmap! {
            "team_length".into()=> 15.into(),
            "team_location".into()=> "cairo".into(),
        };

        let update_team_pref = Teams::update_prefs(
            &client,
            &create_team.id,
            maplit::hashmap! {
                "prefs".into() => Value::Object(prefs_val.clone().into_iter().collect::<Map<String, Value>>()),
            },
        )
        .await?;
        assert_eq!(update_team_pref.data, prefs_val);

        // ! update team
        let update_team = Teams::update_name(
            &client,
            &create_team.id,
            maplit::hashmap! {
                "name".into()=> "chicago org".into(),
            },
        )
        .await?;
        assert_eq!(update_team.clone().name, "chicago org");

        // ! remove members
        let remove_member =
            Teams::delete_memberships(&client, &create_team.id, &membership_ids[0]).await?;
        assert_eq!(remove_member, ());

        // ! delete team and members
        let delete_team = Teams::delete(&client, &create_team.id).await?;
        assert_eq!(delete_team, ());
        let delete_user1 = Users::delete(&client, &create_user1.id).await?;
        assert_eq!(delete_user1, ());
        let delete_user2 = Users::delete(&client, &create_user2.id).await?;
        assert_eq!(delete_user2, ());

        Ok(())
    }
}