subgraph/data_sources/mongo/services/create_one/
mod.rs1use async_graphql::{Error, ErrorExtensions, Result};
2use bson::{doc, Document};
3use log::{debug, info};
4use mongodb::Database;
5
6use super::Services;
7
8impl Services {
9 pub async fn create_one(
10 db: Database,
11 input: Document,
12 collection: String,
13 ) -> Result<Option<Document>, async_graphql::Error> {
14 info!("Executing Create One");
15
16 let coll = db.collection::<Document>(&collection);
17
18 let values_input = match input.get("values") {
19 Some(values_input) => values_input,
20 None => return Err(Error::new("Values input not found")),
21 };
22
23 let values_input_doc = match values_input.as_document() {
24 Some(values_input_doc) => values_input_doc,
25 None => return Err(Error::new("Values input not found")),
26 };
27
28 let insert_one_result = coll
29 .insert_one(values_input_doc, None)
30 .await
31 .expect("Failed to create document.");
32
33 let document = coll
34 .find_one(doc! {"_id": insert_one_result.inserted_id }, None)
35 .await;
36
37 if let Ok(doc_exists) = document {
38 if let Some(user_document) = doc_exists {
39 Ok(Some(user_document))
40 } else {
41 Err(Error::new("Document not found")
42 .extend_with(|err, e| e.set("details", err.message.as_str())))
43 }
44 } else {
45 info!("Dastabase Error");
46 debug!("{:?}", document);
47 Err(Error::new("Database Error"))
48 }
49 }
50}