1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
use std::{fs, path::Path};

use crate::errors::Result;
use anyhow::Ok;
use mongodb::bson::Document;

pub fn read_json<P: AsRef<Path>>(p: P) -> Result<serde_json::Value> {
    let s = fs::read_to_string(p)?;
    let j = serde_json::from_str(&s)?;
    Ok(j)
}


pub fn str_to_bson(s: &str) -> Result<Document> {
    let m: serde_json::Map<String, serde_json::value::Value> = serde_json::from_str(s)?;
    let d = Document::try_from(m)?;
    Ok(d)
}

#[cfg(test)]
mod tests {

    #[test]
    fn test_s() {
        let s = r###"
        {
            "createRole": "myClusterwideAdmin",
            "privileges": [
                {
                    "resource": {
                        "cluster": true
                    },
                    "actions": [
                        "addShard"
                    ]
                }
            ],
            "roles": [
                {
                    "role": "read",
                    "db": "admin"
                }
            ]
        }
        "###;
        let d = super::str_to_bson(s);
        assert!(d.is_ok());
        println!("{}", d.unwrap());
    }
}