2.8 KiB · text History 263b40b
//! `/api/v1`: the JSON API the Android app talks to (docs/api.md).
//!
//! Handlers here are thin. Who may see a category, whether an account may
//! write, how a view is counted and a topic marked read, how a list is sorted
//! and filtered — all of it is the web's code, called from here as the web
//! handlers call it (`crate::actions` for writes, the listing helpers in
//! `crate::handlers` for reads). See docs/android.md §2a.
use std::sync::Arc;

use axum::extract::DefaultBodyLimit;
use axum::routing::{delete, get, post, put};
use axum::Router;
use sea_orm::DatabaseConnection;

use crate::middleware::api_auth_middleware;
use crate::AppState;

mod error;
pub mod find;
pub mod forum;
mod json;
pub mod me;
pub mod views;

pub use error::{ApiError, ApiResult};
pub use json::{ApiJson, ApiPath};

/// The API's routes, to be nested at `/api/v1`. Every one needs a device
/// token; there is no anonymous API (the web is for browsing signed out).
pub fn router(db: Arc<DatabaseConnection>) -> Router<AppState> {
    // An avatar may be up to 5 MB; axum's default body cap is 2 MB.
    let avatar_limit = DefaultBodyLimit::max(crate::actions::MAX_AVATAR_BYTES + 64 * 1024);
    Router::new()
        .route("/me", get(me::show).patch(me::update))
        .route("/me/avatar", put(me::set_avatar).delete(me::clear_avatar).layer(avatar_limit))
        .route("/me/verification", post(me::resend_verification))
        .route("/me/devices", get(me::devices))
        .route("/me/devices/{id}", delete(me::revoke_device))
        .route("/sessions/current", delete(me::sign_out))
        .route("/categories", get(forum::categories))
        .route("/categories/{slug}", get(forum::category))
        .route("/categories/{slug}/watch", put(forum::set_watch))
        .route("/categories/{slug}/topics", post(forum::create_topic))
        .route("/topics/{id}", get(forum::topic))
        .route("/topics/{id}/posts", post(forum::reply))
        .route("/topics/{id}/tags", put(forum::set_tags))
        .route("/posts/{id}/reaction", put(forum::set_reaction))
        .route("/posts/{id}/bookmark", put(forum::set_bookmark))
        .route("/posts/{id}/flags", post(forum::flag))
        .route("/tags", get(find::index))
        .route("/tags/{slug}", get(find::show))
        .route("/search", get(find::search))
        .route("/bookmarks", get(find::bookmarks))
        .route("/notifications", get(find::notifications))
        .route("/notifications/unread", get(find::unread))
        .route("/notifications/read", post(find::mark_all_read))
        .route("/notifications/{id}/read", post(find::mark_read))
        .layer(axum::middleware::from_fn_with_state(db, api_auth_middleware))
        // An unknown path under /api/v1 is a JSON 404 too, not an empty body.
        .fallback(|| async { ApiError::not_found("No such endpoint.") })
}