-
Notifications
You must be signed in to change notification settings - Fork 0
/
resources.rs
98 lines (89 loc) · 2.7 KB
/
resources.rs
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
94
95
96
97
98
use super::controller::Controller;
use crate::{
auth::claims::AdminClaims, models::resource_data::Resource,
repositories::resources::repo::ResourcesRepo,
};
use petompp_web_models::{
error::{ApiError, Error, ResourceDataValidationError, ValidationError},
models::{api_response::ApiResponse, country::Country, resource_data::ResourceData},
};
use rocket::{delete, get, post, put, routes, serde::json::Json};
pub struct ResourcesController;
impl Controller for ResourcesController {
fn path(&self) -> &'static str {
"/res"
}
fn routes(&self) -> Vec<rocket::Route> {
routes![get, get_all_keys, create, update, delete, delete_lang]
}
}
#[get("/<key>?<lang>")]
async fn get<'a>(
key: &'a str,
lang: Country,
pool: &dyn ResourcesRepo,
) -> Result<Json<ApiResponse<'a, (Country, String)>>, ApiError<'a>> {
Ok(Json(ApiResponse::ok(pool.get(key, &lang)?)))
}
#[get("/keys")]
async fn get_all_keys<'a>(
pool: &dyn ResourcesRepo,
) -> Result<Json<ApiResponse<'a, Vec<String>>>, ApiError<'a>> {
Ok(Json(ApiResponse::ok(
pool.get_all()?
.iter()
.map(|x| x.key.clone().unwrap())
.collect(),
)))
}
#[put("/<key>", data = "<value>")]
async fn create<'a>(
_admin_claims: AdminClaims,
key: &'a str,
value: Json<ResourceData>,
pool: &dyn ResourcesRepo,
) -> Result<Json<ApiResponse<'a, ResourceData>>, ApiError<'a>> {
let value = Resource {
key: Some(key.to_string()),
..value.into_inner().into()
};
Ok(Json(ApiResponse::ok(pool.create(&value)?.into())))
}
#[post("/<key>", data = "<value>")]
async fn update<'a>(
_admin_claims: AdminClaims,
key: &'a str,
value: Json<ResourceData>,
pool: &dyn ResourcesRepo,
) -> Result<Json<ApiResponse<'a, ResourceData>>, ApiError<'a>> {
if key != value.key.as_str() {
return Err(Error::Validation(ValidationError::ResourceData(
ResourceDataValidationError::KeyMismatch(key.to_string(), value.key.clone()),
))
.into());
}
let value = Resource {
key: Some(key.to_string()),
..value.into_inner().into()
};
Ok(Json(ApiResponse::ok(pool.update(&value)?.into())))
}
#[delete("/<key>")]
async fn delete<'a>(
_admin_claims: AdminClaims,
key: &'a str,
pool: &dyn ResourcesRepo,
) -> Result<Json<ApiResponse<'a, &'a str>>, ApiError<'a>> {
pool.delete(key)?;
Ok(Json(ApiResponse::ok("ok")))
}
#[delete("/<key>?<lang>")]
async fn delete_lang<'a>(
_admin_claims: AdminClaims,
key: &'a str,
lang: Country,
pool: &dyn ResourcesRepo,
) -> Result<Json<ApiResponse<'a, &'a str>>, ApiError<'a>> {
pool.delete_lang(key, &lang)?;
Ok(Json(ApiResponse::ok("ok")))
}