mongodb_command_cli/utils/
ser.rs

1use std::{fs, path::Path};
2
3use crate::errors::Result;
4use anyhow::Ok;
5use mongodb::bson::Document;
6
7pub fn read_json<P: AsRef<Path>>(p: P) -> Result<serde_json::Value> {
8    let s = fs::read_to_string(p)?;
9    let j = serde_json::from_str(&s)?;
10    Ok(j)
11}
12
13
14pub fn str_to_bson(s: &str) -> Result<Document> {
15    let m: serde_json::Map<String, serde_json::value::Value> = serde_json::from_str(s)?;
16    let d = Document::try_from(m)?;
17    Ok(d)
18}
19
20#[cfg(test)]
21mod tests {
22
23    #[test]
24    fn test_s() {
25        let s = r###"
26        {
27            "createRole": "myClusterwideAdmin",
28            "privileges": [
29                {
30                    "resource": {
31                        "cluster": true
32                    },
33                    "actions": [
34                        "addShard"
35                    ]
36                }
37            ],
38            "roles": [
39                {
40                    "role": "read",
41                    "db": "admin"
42                }
43            ]
44        }
45        "###;
46        let d = super::str_to_bson(s);
47        assert!(d.is_ok());
48        println!("{}", d.unwrap());
49    }
50}