Skip to main content

admin_demo/
admin_demo.rs

1use std::net::SocketAddr;
2
3use rustio_core::admin;
4use rustio_core::auth::authenticate;
5use rustio_core::defaults::with_defaults;
6use rustio_core::{Db, Error, Model, Row, Router, RustioAdmin, Server, Value};
7
8#[derive(Debug, RustioAdmin)]
9struct User {
10    id: i64,
11    name: String,
12    is_admin: bool,
13}
14
15impl Model for User {
16    const TABLE: &'static str = "users";
17    const COLUMNS: &'static [&'static str] = &["id", "name", "is_admin"];
18    const INSERT_COLUMNS: &'static [&'static str] = &["name", "is_admin"];
19
20    fn id(&self) -> i64 {
21        self.id
22    }
23
24    fn from_row(row: Row<'_>) -> Result<Self, Error> {
25        Ok(Self {
26            id: row.get_i64("id")?,
27            name: row.get_string("name")?,
28            is_admin: row.get_bool("is_admin")?,
29        })
30    }
31
32    fn insert_values(&self) -> Vec<Value> {
33        vec![self.name.clone().into(), self.is_admin.into()]
34    }
35}
36
37#[tokio::main]
38async fn main() -> std::io::Result<()> {
39    let db = Db::memory().await.expect("db connect");
40    db.execute(
41        "CREATE TABLE users (
42            id INTEGER PRIMARY KEY AUTOINCREMENT,
43            name TEXT NOT NULL,
44            is_admin INTEGER NOT NULL
45        )",
46    )
47    .await
48    .expect("create schema");
49
50    User { id: 0, name: "Alice".into(), is_admin: false }
51        .create(&db)
52        .await
53        .expect("seed alice");
54    User { id: 0, name: "Bob".into(), is_admin: true }
55        .create(&db)
56        .await
57        .expect("seed bob");
58
59    let router = with_defaults(Router::new()).wrap(authenticate);
60    let router = admin::register::<User>(router, &db);
61
62    let addr: SocketAddr = ([127, 0, 0, 1], 3000).into();
63    eprintln!("admin demo: hit /admin/users with `Authorization: Bearer dev-admin` header");
64    Server::bind(addr).serve_router(router).await
65}