H2CO3 / magnet

A JSON/BSON schema generator
MIT License
17 stars 4 forks source link
bson crates database json-schema mongodb schema

Magnet, a JSON schema generator

Magnet on crates.io Magnet on docs.rs Magnet Download Magnet License Lines of Code Twitter

These two related crates, magnet_derive and magnet_schema help you define (and, in most cases, automatically derive) MongoDB-flavored JSON schemas for your domain model types. Currently, the primary use case for this library is to make it easy to validate serializeable types when using Avocado or the MongoDB Rust driver.

The defined BsonSchema trait defines a single function, bson_schema, which should/will return a Bson Document that is a valid JSON schema describing the structure of the implementing type. Example:

#[macro_use]
extern crate serde_derive;
extern crate serde;
#[macro_use]
extern crate bson;
#[macro_use]
extern crate magnet_derive;
extern crate magnet_schema;
extern crate mongodb;

use std::collections::HashSet;
use magnet_schema::BsonSchema;

use mongodb::{ Client, ThreadedClient, CommandType };
use mongodb::db::{ ThreadedDatabase };

#[derive(BsonSchema)]
struct Person {
    name: String,
    nicknames: HashSet<String>,
    age: usize,
    contact: Option<Contact>,
}

#[derive(BsonSchema, Serialize, Deserialize)]
#[serde(tag = "type", content = "value")]
enum Contact {
    Email(String),
    Phone(u64),
}

fn main() {
    let schema = Person::bson_schema();
    let spec = doc! {
        "create": "Person",
        "validator": { "$jsonSchema": schema },
    };
    let client = Client::connect("localhost", 27017).expect("can't connect to mongod");
    let db = client.db("Example");
    db.command(spec, CommandType::CreateCollection, None).expect("network error");
    // etc.
}

For milestones and custom #[attributes], please see the documentation.

Release Notes

v0.8.0

v0.7.0

v0.6.0

v0.5.0

v0.4.0

v0.3.3

v0.3.2

v0.3.1

v0.3.0

v0.2.1

v0.2.0

v0.1.4

v0.1.3

v0.1.2

v0.1.1

v0.1.0