glacier-web 0.2.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! OpenAPI from controllers, serializers and models.

use glacier::db::{BelongsTo, Repo};
use glacier::prelude::*;
use serde_json::json as js;

#[glacier::model]
pub struct Author {
    name: String,
}

#[glacier::enumeration]
pub enum Status {
    Draft,
    Published,
}

#[glacier::model]
pub struct Book {
    #[validate(required)]
    title: String,
    price: Option<Decimal>,
    status: Status,
    author_id: i64,
    #[glacier(protected)]
    featured: bool,
    #[glacier(belongs_to)]
    author: BelongsTo<Author>,
}

/// As `.glacier` compiles `serializer BookSerializer do … end`.
pub struct BookSerializer;
impl glacier::Serializer for BookSerializer {
    type Model = Book;
    fn serialize(object: &Book) -> serde_json::Value {
        Self::__fields(Some(object), glacier::serialize::Object::new())
    }
    fn schema() -> serde_json::Value {
        Self::__fields(None, glacier::serialize::Object::schema())
    }
}
impl BookSerializer {
    pub fn __fields(
        object: Option<&Book>,
        mut __json: glacier::serialize::Object,
    ) -> serde_json::Value {
        glacier::__serializer_attr!(__json, object, "id", object.id);
        glacier::__serializer_attr!(__json, object, "title", object.title);
        glacier::__serializer_attr!(__json, object, "price", object.price);
        glacier::__serializer_attr!(__json, object, "status", object.status);
        glacier::__serializer_value!(__json, object, "shout", object.title.to_uppercase());
        glacier::__serializer_assoc!(__json, object, one, "author", object.author);
        __json.into_json()
    }
}

pub struct Books;

#[glacier::controller]
impl Books {
    async fn index(ctx: Context) -> Result<Response> {
        let page = glacier::pagination::Page::from_params(&ctx.params(), 10);
        let books = page.of(Book::all()).all().await?;
        json!(books, each_serializer = BookSerializer)
    }

    async fn show(ctx: Context) -> Result<Response> {
        let book = Book::find(ctx.id()?).await?;
        json!(book, serializer = BookSerializer, root = "data")
    }

    async fn create(ctx: Context) -> Result<Response> {
        let mut book = Book::build(ctx.params().require("book")?);
        if book.save().await? {
            json!(book, serializer = BookSerializer, status = "created")
        } else {
            json!(book.errors_json(), status = 422)
        }
    }

    /// Paths and constructors that aren't models: `Vec::new`, a full path.
    async fn update(ctx: Context) -> Result<Response> {
        let mut errors: Vec<String> = Vec::new();
        let mut object = ::glacier::serialize::Object::new();
        let params = ctx.params().require("book")?;
        if params.get("title").is_none() {
            errors.push("title".into());
        }
        object.value("errors", &errors);
        let book = Book::find(ctx.id()?).await?;
        let _ = book;
        json!(object.into_json())
    }

    async fn destroy(ctx: Context) -> Result<Response> {
        Book::find(ctx.id()?).await?.delete().await?;
        Ok(Response::head(StatusCode::NO_CONTENT))
    }
}

fn spec() -> serde_json::Value {
    let app = App::new().routes(|r| {
        r.document::<Books>();
        r.resources::<Books>("/books");
        r.scope("/v1", |r| {
            r.document::<Books>();
            r.get("/books/:id", Books::show).constrain("id", r"\d+");
        });
    });
    glacier::openapi::document(app.build().router(), "shop", "1.2.0", None)
}

#[test]
fn models_and_serializers_have_schemas() {
    use glacier::serialize::Schema;
    let book = Book::schema();
    assert_eq!(book["properties"]["title"], js!({"type": "string"}));
    assert_eq!(
        book["properties"]["status"],
        js!({"type": "string", "enum": ["draft", "published"]})
    );
    assert_eq!(
        book["properties"]["price"],
        js!({"type": ["string", "null"], "format": "decimal"})
    );
    let params = Book::params_schema();
    let names: Vec<&String> = params["properties"].as_object().unwrap().keys().collect();
    assert_eq!(
        names,
        ["title", "price", "status", "author_id"],
        "not protected ones"
    );

    let serialized = <BookSerializer as glacier::Serializer>::schema();
    assert_eq!(
        serialized["required"],
        js!(["id", "title", "price", "status", "shout", "author"])
    );
    assert_eq!(serialized["properties"]["shout"], js!({"type": "string"}));
    assert_eq!(
        serialized["properties"]["author"]["type"],
        js!(["object", "null"])
    );
    assert_eq!(
        serialized["properties"]["author"]["properties"]["name"],
        js!({"type": "string"})
    );
}

#[glacier::test]
async fn serializers_still_write_records() {
    let repo = Repo::connect("sqlite::memory:").await.unwrap();
    let _ = repo;
    let mut book = Book::new();
    book.title = "Dune".into();
    let json = <BookSerializer as glacier::Serializer>::serialize(&book);
    assert_eq!(json["title"], "Dune");
    assert_eq!(json["shout"], "DUNE");
    assert_eq!(json["status"], "draft");
    assert_eq!(json["author"], serde_json::Value::Null);
}

#[test]
fn documents_routes_from_controllers() {
    let spec = spec();
    assert_eq!(spec["openapi"], "3.1.0");
    assert_eq!(spec["info"], js!({"title": "shop", "version": "1.2.0"}));
    let index = &spec["paths"]["/books"]["get"];
    assert_eq!(index["operationId"], "books_index");
    let query: Vec<&str> = index["parameters"]
        .as_array()
        .unwrap()
        .iter()
        .map(|p| p["name"].as_str().unwrap())
        .collect();
    assert_eq!(query, ["page", "per_page"]);
    assert_eq!(
        index["responses"]["200"]["content"]["application/json"]["schema"],
        js!({
            "type": "object",
            "properties": {"books": {"type": "array", "items": {"$ref": "#/components/schemas/Book"}}},
            "required": ["books"],
        })
    );

    let create = &spec["paths"]["/books"]["post"];
    let statuses: Vec<&String> = create["responses"].as_object().unwrap().keys().collect();
    assert_eq!(statuses, ["201", "422", "400"]);
    assert_eq!(
        create["requestBody"]["content"]["application/json"]["schema"]["properties"]["book"],
        Book::params_schema()
    );

    let show = &spec["paths"]["/books/{id}"]["get"];
    assert!(show["responses"]["404"].is_object());
    assert_eq!(
        show["responses"]["200"]["content"]["application/json"]["schema"]["properties"]["data"],
        js!({"$ref": "#/components/schemas/Book"}),
        "root = \"data\""
    );
    assert_eq!(
        spec["paths"]["/books/{id}"]["delete"]["responses"],
        js!({"204": {"description": "No Content"}, "404": spec["paths"]["/books/{id}"]["delete"]["responses"]["404"]})
    );

    let update = &spec["paths"]["/books/{id}"]["patch"];
    assert_eq!(
        update["requestBody"]["content"]["application/json"]["schema"]["properties"]["book"],
        Book::params_schema(),
        "the model is Book, not Vec or Object"
    );

    let v1 = &spec["paths"]["/v1/books/{id}"]["get"];
    assert_eq!(v1["operationId"], "v1_books_show");
    assert_eq!(v1["parameters"][0]["schema"], js!({"type": "integer"}));
    assert_eq!(
        spec["components"]["schemas"]["Book"],
        <BookSerializer as glacier::Serializer>::schema()
    );
}

mod versions {
    use super::*;

    pub struct Widgets;

    #[glacier::controller]
    impl Widgets {
        async fn index() -> Result<&'static str> {
            Ok("v1")
        }
    }

    pub struct WidgetsV2;

    #[glacier::controller]
    impl WidgetsV2 {
        async fn index() -> Result<&'static str> {
            Ok("v2")
        }
    }

    mod routes {
        use super::{Widgets, WidgetsV2};

        glacier::routes! {
            scope "/" version "1", default {
                get "/widgets" => Widgets::index;
            }
            scope "/" version "2" {
                get "/widgets" => WidgetsV2::index;
            }
            get "/health" => Widgets::index;
            // Unversioned first, but version 2 asks for its own.
            get "/both" => Widgets::index;
            scope "/" version "2" {
                get "/both" => WidgetsV2::index;
            }
        }
    }

    fn client() -> glacier::testing::TestClient {
        glacier::testing::TestClient::new(App::new().routes(routes::draw))
    }

    async fn get(client: &glacier::testing::TestClient, headers: &[(&str, &str)]) -> (u16, String) {
        let mut request = http::Request::get("/widgets");
        for (name, value) in headers {
            request = request.header(*name, *value);
        }
        let res = client
            .request(request.body(Default::default()).unwrap())
            .await;
        (res.status().as_u16(), res.body_text())
    }

    #[glacier::test]
    async fn requests_pick_their_version() {
        let client = client();
        assert_eq!(get(&client, &[]).await, (200, "v1".into()), "the default");
        assert_eq!(
            get(&client, &[("api-version", "2")]).await,
            (200, "v2".into())
        );
        assert_eq!(
            get(&client, &[("api-version", "v1")]).await,
            (200, "v1".into())
        );
        assert_eq!(
            get(&client, &[("accept", "application/vnd.shop.v2+json")]).await,
            (200, "v2".into())
        );
        assert_eq!(
            get(&client, &[("accept", "application/json; version=2")]).await,
            (200, "v2".into())
        );
        assert_eq!(get(&client, &[("api-version", "3")]).await.0, 404);
        assert_eq!(
            client.get("/health").await.body_text(),
            "v1",
            "unversioned routes answer every version"
        );
        let both = |version: &'static str| {
            let request = http::Request::get("/both").header("api-version", version);
            client.request(request.body(Default::default()).unwrap())
        };
        assert_eq!(both("2").await.body_text(), "v2");
        assert_eq!(both("1").await.body_text(), "v1");
        assert_eq!(client.get("/both").await.body_text(), "v1");
    }

    #[test]
    fn each_version_has_its_document() {
        let app = App::new().routes(routes::draw).build();
        let default = glacier::openapi::document(app.router(), "shop", "1.2.0", None);
        assert_eq!(
            default["paths"]["/widgets"]["get"]["operationId"],
            "widgets_index"
        );
        assert_eq!(default["info"]["version"], "1.2.0");
        let two = glacier::openapi::document(app.router(), "shop", "1.2.0", Some("2"));
        let widgets = &two["paths"]["/widgets"]["get"];
        assert_eq!(widgets["operationId"], "widgets_v2_index");
        assert_eq!(widgets["parameters"][0]["name"], "Api-Version");
        assert_eq!(widgets["parameters"][0]["schema"]["enum"], js!(["2"]));
        assert_eq!(two["info"]["version"], "2");
        assert!(two["paths"]["/health"].is_object());
        assert_eq!(
            two["paths"]["/both"]["get"]["operationId"],
            "both_widgets_v2_index"
        );
        assert_eq!(
            default["paths"]["/both"]["get"]["operationId"],
            "both_widgets_index"
        );
    }
}