Skip to main content

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

1//! Create a Microsoft Graph draft message (`POST /me/messages` or
2//! `POST /me/mailFolders/{id}/messages`).
3//!
4//! <https://learn.microsoft.com/en-us/graph/api/user-post-messages>
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::messages::MsgraphMessage,
17        send::{MSGRAPH_API_BASE, MsgraphSend, MsgraphSendError, MsgraphSendOutput, user_path},
18    },
19};
20
21/// Creates a Microsoft Graph draft message from JSON.
22pub struct MsgraphMessageCreate {
23    send: MsgraphSend<MsgraphMessage>,
24}
25
26impl MsgraphMessageCreate {
27    /// Creates the draft in the Drafts folder, or in `folder` when given
28    /// (a folder id or a well-known name such as `drafts`).
29    pub fn new(
30        auth: &HttpAuthBearer,
31        user_id: &str,
32        folder: Option<&str>,
33        message: &MsgraphMessage,
34    ) -> Result<Self, MsgraphSendError> {
35        debug!("prepare microsoft graph message for creation");
36        trace!("folder: {folder:?}");
37        trace!("message: {message:?}");
38
39        let user = user_path(user_id);
40        let path = match folder {
41            Some(folder) => format!("{user}/mailFolders/{folder}/messages"),
42            None => format!("{user}/messages"),
43        };
44        let url = Url::parse(MSGRAPH_API_BASE)?.join(&path)?;
45        let send = MsgraphSend::post_json(auth, url, message)?;
46
47        Ok(Self { send })
48    }
49}
50
51impl MsgraphCoroutine for MsgraphMessageCreate {
52    type Yield = MsgraphYield;
53    type Return = Result<MsgraphSendOutput<MsgraphMessage>, 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!("message created");
58        trace!("out: {out:?}");
59        MsgraphCoroutineState::Complete(Ok(out))
60    }
61}