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::{
18            MSGRAPH_API_BASE, MsgraphSend, MsgraphSendError, MsgraphSendOutput, path_segment,
19            user_path,
20        },
21    },
22};
23
24/// Creates a Microsoft Graph contact.
25pub struct MsgraphContactCreate {
26    send: MsgraphSend<MsgraphContact>,
27}
28
29impl MsgraphContactCreate {
30    /// Creates the contact in the default Contacts folder, or in
31    /// `folder` when given (a contact folder id).
32    pub fn new(
33        auth: &HttpAuthBearer,
34        user_id: &str,
35        folder: Option<&str>,
36        contact: &MsgraphContact,
37    ) -> Result<Self, MsgraphSendError> {
38        debug!("prepare microsoft graph contact for creation");
39        trace!("folder: {folder:?}");
40        trace!("contact: {contact:?}");
41
42        let user = user_path(user_id)?;
43        let path = match folder {
44            Some(folder) => format!("{user}/contactFolders/{}/contacts", path_segment(folder)?),
45            None => format!("{user}/contacts"),
46        };
47        let url = Url::parse(MSGRAPH_API_BASE)?.join(&path)?;
48        let send = MsgraphSend::post_json(auth, url, contact)?;
49
50        Ok(Self { send })
51    }
52}
53
54impl MsgraphCoroutine for MsgraphContactCreate {
55    type Yield = MsgraphYield;
56    type Return = Result<MsgraphSendOutput<MsgraphContact>, MsgraphSendError>;
57
58    fn resume(&mut self, arg: Option<&[u8]>) -> MsgraphCoroutineState<Self::Yield, Self::Return> {
59        let out = msgraph_try!(&mut self.send, arg);
60        debug!("contact created");
61        trace!("out: {out:?}");
62        MsgraphCoroutineState::Complete(Ok(out))
63    }
64}