Skip to main content

io_msgraph/v1/rest/users/contacts/
create.rs

1//! Create a Microsoft Graph contact (`POST /me/contacts` or
2//! `POST /me/contactFolders/{id}/contacts`).
3//!
4//! <https://learn.microsoft.com/en-us/graph/api/user-post-contacts>
5
6use alloc::format;
7
8use io_http::rfc6750::bearer::HttpAuthBearer;
9use log::{debug, trace};
10use url::Url;
11
12use crate::{
13    coroutine::*,
14    msgraph_try,
15    v1::{
16        rest::users::contacts::MsgraphContact,
17        send::{MSGRAPH_API_BASE, MsgraphSend, MsgraphSendError, MsgraphSendOutput, user_path},
18    },
19};
20
21/// Creates a Microsoft Graph contact.
22pub struct MsgraphContactCreate {
23    send: MsgraphSend<MsgraphContact>,
24}
25
26impl MsgraphContactCreate {
27    /// Creates the contact in the default Contacts folder, or in
28    /// `folder` when given (a contact folder id).
29    pub fn new(
30        auth: &HttpAuthBearer,
31        user_id: &str,
32        folder: Option<&str>,
33        contact: &MsgraphContact,
34    ) -> Result<Self, MsgraphSendError> {
35        debug!("prepare microsoft graph contact for creation");
36        trace!("folder: {folder:?}");
37        trace!("contact: {contact:?}");
38
39        let user = user_path(user_id);
40        let path = match folder {
41            Some(folder) => format!("{user}/contactFolders/{folder}/contacts"),
42            None => format!("{user}/contacts"),
43        };
44        let url = Url::parse(MSGRAPH_API_BASE)?.join(&path)?;
45        let send = MsgraphSend::post_json(auth, url, contact)?;
46
47        Ok(Self { send })
48    }
49}
50
51impl MsgraphCoroutine for MsgraphContactCreate {
52    type Yield = MsgraphYield;
53    type Return = Result<MsgraphSendOutput<MsgraphContact>, MsgraphSendError>;
54
55    fn resume(&mut self, arg: Option<&[u8]>) -> MsgraphCoroutineState<Self::Yield, Self::Return> {
56        let out = msgraph_try!(&mut self.send, arg);
57        debug!("contact created");
58        trace!("out: {out:?}");
59        MsgraphCoroutineState::Complete(Ok(out))
60    }
61}