Skip to main content

glacier/
controller.rs

1//! Rails-style resource controllers.
2
3use std::future::Future;
4
5use crate::context::Context;
6use crate::error::{Error, Result};
7use crate::response::Response;
8
9/// The seven conventional RESTful actions.
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum Action {
12    Index,
13    New,
14    Create,
15    Show,
16    Edit,
17    Update,
18    Destroy,
19}
20
21impl Action {
22    pub const ALL: &'static [Action] = &[
23        Action::Index,
24        Action::New,
25        Action::Create,
26        Action::Show,
27        Action::Edit,
28        Action::Update,
29        Action::Destroy,
30    ];
31}
32
33/// A controller for a RESTful resource, mounted with `Router::resources`.
34///
35/// Every action defaults to `404 Not Found`, so implement only the ones you
36/// need (and use `Router::resources_only` to avoid registering the rest):
37///
38/// ```
39/// use glacier::prelude::*;
40///
41/// struct Posts;
42///
43/// impl Resource for Posts {
44///     async fn index(_ctx: Context) -> Result<Response> {
45///         Ok(Response::text("all posts"))
46///     }
47///
48///     async fn show(ctx: Context) -> Result<Response> {
49///         let id: u64 = ctx.param_as("id")?;
50///         Ok(Response::text(format!("post {id}")))
51///     }
52/// }
53/// ```
54pub trait Resource: Send + Sync + 'static {
55    /// The actions `Router::resources` mounts. `#[glacier::controller]`
56    /// sets this to the actions that are actually defined.
57    const ACTIONS: &'static [Action] = Action::ALL;
58
59    /// `GET /name`
60    fn index(_ctx: Context) -> impl Future<Output = Result<Response>> + Send {
61        async { Err(Error::not_found()) }
62    }
63
64    /// `GET /name/new`
65    fn new(_ctx: Context) -> impl Future<Output = Result<Response>> + Send {
66        async { Err(Error::not_found()) }
67    }
68
69    /// `POST /name`
70    fn create(_ctx: Context) -> impl Future<Output = Result<Response>> + Send {
71        async { Err(Error::not_found()) }
72    }
73
74    /// `GET /name/:id`
75    fn show(_ctx: Context) -> impl Future<Output = Result<Response>> + Send {
76        async { Err(Error::not_found()) }
77    }
78
79    /// `GET /name/:id/edit`
80    fn edit(_ctx: Context) -> impl Future<Output = Result<Response>> + Send {
81        async { Err(Error::not_found()) }
82    }
83
84    /// `PATCH /name/:id` and `PUT /name/:id`
85    fn update(_ctx: Context) -> impl Future<Output = Result<Response>> + Send {
86        async { Err(Error::not_found()) }
87    }
88
89    /// `DELETE /name/:id`
90    fn destroy(_ctx: Context) -> impl Future<Output = Result<Response>> + Send {
91        async { Err(Error::not_found()) }
92    }
93}