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