chore: normalize code
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
use axum::{
|
||||
Router,
|
||||
routing::{delete, get, post, put},
|
||||
};
|
||||
|
||||
pub mod roles_controller;
|
||||
pub mod roles_dto;
|
||||
pub mod roles_enum;
|
||||
pub mod roles_repository;
|
||||
pub mod roles_schema;
|
||||
pub mod roles_service;
|
||||
|
||||
pub use roles_controller::*;
|
||||
pub use roles_dto::*;
|
||||
pub use roles_enum::*;
|
||||
pub use roles_repository::*;
|
||||
pub use roles_schema::*;
|
||||
pub use roles_service::*;
|
||||
|
||||
pub fn roles_router() -> Router {
|
||||
Router::new()
|
||||
.route("/", get(get_role_list))
|
||||
.route("/detail/{id}", get(get_role_by_id))
|
||||
.route("/create", post(post_create_role))
|
||||
.route("/update/{id}", put(put_update_role))
|
||||
.route("/delete/{id}", delete(delete_role))
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
use axum::{
|
||||
extract::{Path, Query},
|
||||
response::IntoResponse,
|
||||
Extension, Json,
|
||||
};
|
||||
|
||||
use super::{RolesItemDto, RolesRequestCreateDto, RolesRequestUpdateDto};
|
||||
use crate::{
|
||||
permissions_guard, v1::roles_service::RolesService, AppState, MessageResponseDto,
|
||||
MetaRequestDto, PermissionsEnum, ResponseListSuccessDto, ResponseSuccessDto,
|
||||
};
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/roles",
|
||||
params(
|
||||
("page" = Option<i64>, Query, description = "Page number"),
|
||||
("per_page" = Option<i64>, Query, description = "Items per page"),
|
||||
("search" = Option<String>, Query, description = "Search keyword"),
|
||||
("sort_by" = Option<String>, Query, description = "Sort by field"),
|
||||
("order" = Option<String>, Query, description = "Order ASC or DESC"),
|
||||
("filter" = Option<String>, Query, description = "Filter value"),
|
||||
("filter_by" = Option<String>, Query, description = "Field to filter by"),
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "Get role list", body = ResponseListSuccessDto<Vec<RolesItemDto>>)
|
||||
),
|
||||
tag = "Roles"
|
||||
)]
|
||||
pub async fn get_role_list(
|
||||
headers: axum::http::HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Query(meta): Query<MetaRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
&headers,
|
||||
state.clone(),
|
||||
vec![PermissionsEnum::ReadListRoles],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => RolesService::get_role_list(&state, meta).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/roles/detail/{id}",
|
||||
params(("id" = String, Path, description = "Role ID")),
|
||||
responses(
|
||||
(status = 200, description = "Get role by ID", body = ResponseSuccessDto<RolesItemDto>)
|
||||
),
|
||||
tag = "Roles"
|
||||
)]
|
||||
pub async fn get_role_by_id(
|
||||
headers: axum::http::HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
&headers,
|
||||
state.clone(),
|
||||
vec![PermissionsEnum::ReadDetailRoles],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => RolesService::get_role_by_id(&state, id).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/roles/create",
|
||||
request_body = RolesRequestCreateDto,
|
||||
responses(
|
||||
(status = 201, description = "Create new role", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Roles"
|
||||
)]
|
||||
pub async fn post_create_role(
|
||||
headers: axum::http::HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<RolesRequestCreateDto>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
&headers,
|
||||
state.clone(),
|
||||
vec![PermissionsEnum::CreateRoles],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => RolesService::create_role(&state, payload).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
put,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/roles/update/{id}",
|
||||
request_body = RolesRequestUpdateDto,
|
||||
responses(
|
||||
(status = 200, description = "Update role", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Roles"
|
||||
)]
|
||||
pub async fn put_update_role(
|
||||
headers: axum::http::HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
Json(payload): Json<RolesRequestUpdateDto>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
&headers,
|
||||
state.clone(),
|
||||
vec![PermissionsEnum::UpdateRoles],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => RolesService::update_role(&state, id, payload).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
delete,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/roles/delete/{id}",
|
||||
responses(
|
||||
(status = 200, description = "Delete role", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Roles"
|
||||
)]
|
||||
pub async fn delete_role(
|
||||
headers: axum::http::HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
&headers,
|
||||
state.clone(),
|
||||
vec![PermissionsEnum::DeleteRoles],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => RolesService::delete_role(&state, id).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
use crate::{PermissionsItemDto, PermissionsQueryDto};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::sql::Thing;
|
||||
use utoipa::ToSchema;
|
||||
use validator::Validate;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct RolesRequestDto {
|
||||
#[validate(length(min = 1, message = "Role name must not be empty"))]
|
||||
pub name: String,
|
||||
pub permissions: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct RolesListItemDto {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub permissions_count: u64,
|
||||
pub created_at: Option<String>,
|
||||
pub updated_at: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct RolesDetailItemDto {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub permissions: Vec<PermissionsItemDto>,
|
||||
pub created_at: Option<String>,
|
||||
pub updated_at: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct RolesDetailQueryDto {
|
||||
pub id: Thing,
|
||||
pub name: String,
|
||||
pub permissions: Vec<PermissionsQueryDto>,
|
||||
pub is_deleted: bool,
|
||||
pub created_at: Option<String>,
|
||||
pub updated_at: Option<String>,
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
use std::fmt;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum RolesEnum {
|
||||
Admin,
|
||||
User,
|
||||
Student,
|
||||
Staf,
|
||||
}
|
||||
|
||||
impl fmt::Display for RolesEnum {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let roles_str = match self {
|
||||
RolesEnum::Admin => "Admin",
|
||||
RolesEnum::User => "User",
|
||||
RolesEnum::Student => "Student",
|
||||
RolesEnum::Staf => "Staf",
|
||||
};
|
||||
write!(f, "{}", roles_str)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
use super::{
|
||||
RolesItemByIdDto, RolesItemByIdDtoRaw, RolesItemDto, RolesItemDtoRaw, RolesRequestCreateDto, RolesRequestUpdateDto, RolesSchema
|
||||
};
|
||||
use crate::{
|
||||
extract_id, get_id, make_thing, query_list_with_meta, AppState, MetaRequestDto,
|
||||
PermissionsItemDto, ResourceEnum, ResponseListSuccessDto,
|
||||
};
|
||||
use anyhow::{bail, Result};
|
||||
use surrealdb::sql::Thing;
|
||||
use surrealdb::Uuid;
|
||||
|
||||
pub struct RolesRepository<'a> {
|
||||
state: &'a AppState,
|
||||
}
|
||||
|
||||
impl<'a> RolesRepository<'a> {
|
||||
pub fn new(state: &'a AppState) -> Self {
|
||||
Self { state }
|
||||
}
|
||||
|
||||
pub async fn query_raw_role_by_id(&self, id: &str) -> Result<RolesSchema> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let role: Option<RolesSchema> =
|
||||
db.select((ResourceEnum::Roles.to_string(), id)).await?;
|
||||
match role {
|
||||
Some(r) if !r.is_deleted => Ok(r),
|
||||
_ => bail!("Role not found"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query_role_list(
|
||||
&self,
|
||||
meta: MetaRequestDto,
|
||||
) -> Result<ResponseListSuccessDto<Vec<RolesItemDto>>> {
|
||||
let mut conditions = vec!["is_deleted = false".into()];
|
||||
if meta.search.is_some() {
|
||||
conditions.push("string::contains(name, $search)".into());
|
||||
}
|
||||
if meta.filter_by.is_some() && meta.filter.is_some() {
|
||||
let filter_by = meta.filter_by.as_ref().unwrap();
|
||||
conditions.push(format!("{} = $filter", filter_by));
|
||||
}
|
||||
let raw_result: ResponseListSuccessDto<Vec<RolesItemDtoRaw>> = query_list_with_meta(
|
||||
&self.state.surrealdb_ws,
|
||||
&ResourceEnum::Roles.to_string(),
|
||||
&meta,
|
||||
conditions,
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
let transformed_data = raw_result
|
||||
.data
|
||||
.into_iter()
|
||||
.map(|role| {
|
||||
RolesItemDto {
|
||||
name: role.name,
|
||||
created_at: role.created_at,
|
||||
updated_at: role.updated_at,
|
||||
permissions: role.permissions
|
||||
.into_iter()
|
||||
.map(|perm| PermissionsItemDto {
|
||||
id: extract_id(&perm.id),
|
||||
name: perm.name,
|
||||
created_at: perm.created_at,
|
||||
updated_at: perm.updated_at,
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
id: extract_id(&role.id),
|
||||
|
||||
}
|
||||
})
|
||||
.collect::<Vec<RolesItemDto>>();
|
||||
let transformed_meta = raw_result.meta;
|
||||
Ok(ResponseListSuccessDto {
|
||||
data: transformed_data,
|
||||
meta: transformed_meta,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn query_role_by_name(&self, name: String) -> Result<RolesItemByIdDto> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let sql = format!(
|
||||
"SELECT *, permissions FROM {} WHERE name = $name AND is_deleted = false LIMIT 1 FETCH permissions",
|
||||
ResourceEnum::Roles.to_string()
|
||||
);
|
||||
let mut result = db.query(sql).bind(("name", name.clone())).await?;
|
||||
let role: Option<RolesItemByIdDtoRaw> = result.take(0)?;
|
||||
let role = match role {
|
||||
Some(r) if !r.is_deleted => r,
|
||||
_ => bail!("Role not found"),
|
||||
};
|
||||
let permissions = role
|
||||
.permissions
|
||||
.into_iter()
|
||||
.map(|perm| PermissionsItemDto {
|
||||
id: extract_id(&perm.id),
|
||||
name: perm.name,
|
||||
created_at: perm.created_at,
|
||||
updated_at: perm.updated_at,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
Ok(RolesItemByIdDto {
|
||||
id: extract_id(&role.id),
|
||||
name: role.name,
|
||||
is_deleted: role.is_deleted,
|
||||
permissions,
|
||||
created_at: role.created_at,
|
||||
updated_at: role.updated_at,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn query_role_by_id(&self, id: String) -> Result<RolesItemByIdDto> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let query = format!(
|
||||
"SELECT *, permissions.* AS permissions
|
||||
FROM app_roles:⟨{}⟩ WHERE is_deleted = false FETCH permissions",
|
||||
id
|
||||
);
|
||||
let mut result = db.query(query).await?;
|
||||
let role: Option<RolesItemByIdDtoRaw> = result.take(0)?;
|
||||
let role = match role {
|
||||
Some(r) if !r.is_deleted => r,
|
||||
_ => bail!("Role not found"),
|
||||
};
|
||||
let permissions = role
|
||||
.permissions
|
||||
.into_iter()
|
||||
.map(|perm| PermissionsItemDto {
|
||||
id: extract_id(&perm.id),
|
||||
name: perm.name,
|
||||
created_at: perm.created_at,
|
||||
updated_at: perm.updated_at,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
Ok(RolesItemByIdDto {
|
||||
id: extract_id(&role.id),
|
||||
name: role.name,
|
||||
is_deleted: role.is_deleted,
|
||||
permissions,
|
||||
created_at: role.created_at,
|
||||
updated_at: role.updated_at,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn query_create_role(
|
||||
&self,
|
||||
payload: RolesRequestCreateDto,
|
||||
) -> Result<String> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
|
||||
let role_id = Uuid::new_v4().to_string();
|
||||
let permission_things: Vec<Thing> = payload
|
||||
.permissions
|
||||
.iter()
|
||||
.map(|id| make_thing(&ResourceEnum::Permissions.to_string(), id))
|
||||
.collect();
|
||||
|
||||
let role = RolesSchema {
|
||||
id: make_thing(&ResourceEnum::Roles.to_string(), &role_id),
|
||||
name: payload.name,
|
||||
is_deleted: false,
|
||||
permissions: permission_things,
|
||||
created_at: Some(crate::get_iso_date()),
|
||||
updated_at: Some(crate::get_iso_date()),
|
||||
};
|
||||
|
||||
let _: Option<RolesSchema> = db
|
||||
.create((&ResourceEnum::Roles.to_string(), role_id))
|
||||
.content(role)
|
||||
.await?;
|
||||
|
||||
Ok("Role with permissions created successfully".into())
|
||||
}
|
||||
|
||||
pub async fn query_update_role(
|
||||
&self,
|
||||
id: String,
|
||||
data: RolesRequestUpdateDto,
|
||||
) -> Result<String> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let thing_id = make_thing(&ResourceEnum::Roles.to_string(), &id);
|
||||
let existing = self.query_raw_role_by_id(&id).await?;
|
||||
if existing.is_deleted {
|
||||
bail!("Role already deleted");
|
||||
}
|
||||
let permissions: Vec<Thing> = if let Some(permission_ids) = &data.permissions {
|
||||
permission_ids
|
||||
.iter()
|
||||
.map(|id| make_thing(&ResourceEnum::Permissions.to_string(), id))
|
||||
.collect()
|
||||
} else {
|
||||
existing
|
||||
.permissions
|
||||
.iter()
|
||||
.map(|p| make_thing(&ResourceEnum::Permissions.to_string(), &p.id.to_raw()))
|
||||
.collect()
|
||||
};
|
||||
let merged = RolesSchema {
|
||||
id: thing_id,
|
||||
name: data.name.unwrap_or(existing.name),
|
||||
permissions,
|
||||
is_deleted: existing.is_deleted,
|
||||
created_at: existing.created_at,
|
||||
updated_at: Some(crate::get_iso_date()),
|
||||
};
|
||||
let record: Option<RolesSchema> =
|
||||
db.update(get_id(&merged.id)?).content(merged).await?;
|
||||
match record {
|
||||
Some(_) => Ok("Success update role".into()),
|
||||
None => bail!("Failed to update role"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query_delete_role(&self, id: String) -> Result<String> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let role_id = make_thing(&ResourceEnum::Roles.to_string(), &id);
|
||||
let role = self.query_role_by_id(role_id.id.to_raw()).await?;
|
||||
if role.is_deleted {
|
||||
bail!("Role already deleted");
|
||||
}
|
||||
let record_key = get_id(&role_id)?;
|
||||
let record: Option<RolesSchema> = db
|
||||
.update(record_key)
|
||||
.merge(serde_json::json!({ "is_deleted": true }))
|
||||
.await?;
|
||||
match record {
|
||||
Some(_) => Ok("Success delete role".into()),
|
||||
None => bail!("Failed to delete role"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::{sql::Thing, Uuid};
|
||||
|
||||
use crate::{make_thing, ResourceEnum};
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct RolesSchema {
|
||||
pub id: Thing,
|
||||
pub name: String,
|
||||
pub is_deleted: bool,
|
||||
pub permissions: Vec<Thing>,
|
||||
pub created_at: Option<String>,
|
||||
pub updated_at: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for RolesSchema {
|
||||
fn default() -> Self {
|
||||
RolesSchema {
|
||||
id: make_thing(
|
||||
&ResourceEnum::Roles.to_string(),
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
permissions: vec![make_thing(
|
||||
&ResourceEnum::Permissions.to_string(),
|
||||
&Uuid::new_v4().to_string(),
|
||||
)],
|
||||
name: String::new(),
|
||||
is_deleted: false,
|
||||
created_at: None,
|
||||
updated_at: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
use super::{RolesRepository, RolesRequestCreateDto, RolesRequestUpdateDto};
|
||||
use crate::{
|
||||
common_response, success_list_response, success_response, validate_request,
|
||||
AppState, MetaRequestDto, ResponseListSuccessDto, ResponseSuccessDto,
|
||||
};
|
||||
use axum::{http::StatusCode, response::Response};
|
||||
|
||||
pub struct RolesService;
|
||||
|
||||
impl RolesService {
|
||||
pub async fn get_role_list(state: &AppState, meta: MetaRequestDto) -> Response {
|
||||
let repo = RolesRepository::new(state);
|
||||
match repo.query_role_list(meta).await {
|
||||
Ok(data) => {
|
||||
let response = ResponseListSuccessDto {
|
||||
data: data.data,
|
||||
meta: data.meta,
|
||||
};
|
||||
success_list_response(response)
|
||||
}
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_role_by_id(state: &AppState, id: String) -> Response {
|
||||
let repo = RolesRepository::new(state);
|
||||
match repo.query_role_by_id(id).await {
|
||||
Ok(role) => success_response(ResponseSuccessDto { data: role }),
|
||||
Err(e) => common_response(StatusCode::NOT_FOUND, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn create_role(
|
||||
state: &AppState,
|
||||
payload: RolesRequestCreateDto,
|
||||
) -> Response {
|
||||
if let Err((status, message)) = validate_request(&payload) {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
let repo = RolesRepository::new(state);
|
||||
match repo.query_role_by_name(payload.name.clone()).await {
|
||||
Ok(_role) => {
|
||||
return common_response(StatusCode::CONFLICT, "Role name already exists");
|
||||
}
|
||||
Err(err) if err.to_string().contains("not found") => {}
|
||||
Err(e) => {
|
||||
return common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string());
|
||||
}
|
||||
}
|
||||
match repo.query_create_role(payload).await {
|
||||
Ok(msg) => common_response(StatusCode::CREATED, &msg),
|
||||
Err(e) => common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn update_role(
|
||||
state: &AppState,
|
||||
id: String,
|
||||
payload: RolesRequestUpdateDto,
|
||||
) -> Response {
|
||||
if let Err((status, message)) = validate_request(&payload) {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
let repo = RolesRepository::new(state);
|
||||
let existing_role = match repo.query_role_by_id(id.clone()).await {
|
||||
Ok(role) => role,
|
||||
Err(err) if err.to_string().contains("not found") => {
|
||||
return common_response(StatusCode::NOT_FOUND, "Role not found");
|
||||
}
|
||||
Err(e) => {
|
||||
return common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string());
|
||||
}
|
||||
};
|
||||
if let Some(new_name) = payload.name.clone() {
|
||||
match repo.query_role_by_name(new_name.clone()).await {
|
||||
Ok(role_with_same_name) => {
|
||||
if role_with_same_name.id != existing_role.id {
|
||||
return common_response(
|
||||
StatusCode::CONFLICT,
|
||||
"Role name already exists",
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(err) if err.to_string().contains("not found") => {}
|
||||
Err(e) => {
|
||||
return common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
match repo.query_update_role(id, payload).await {
|
||||
Ok(msg) => common_response(StatusCode::OK, &msg),
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn delete_role(state: &AppState, id: String) -> Response {
|
||||
let repo = RolesRepository::new(state);
|
||||
match repo.query_role_by_id(id.clone()).await {
|
||||
Ok(_) => {}
|
||||
Err(err) if err.to_string().contains("not found") => {
|
||||
return common_response(StatusCode::NOT_FOUND, "Role not found");
|
||||
}
|
||||
Err(e) => {
|
||||
return common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string());
|
||||
}
|
||||
}
|
||||
match repo.query_delete_role(id).await {
|
||||
Ok(msg) => common_response(StatusCode::OK, &msg),
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user