chore: normalize code #2
This commit is contained in:
@@ -17,6 +17,17 @@ pub struct PermissionsItemDto {
|
|||||||
pub updated_at: Option<String>,
|
pub updated_at: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl PermissionsItemDto {
|
||||||
|
pub fn from(dto: &PermissionsQueryDto) -> Self {
|
||||||
|
Self {
|
||||||
|
id: dto.id.id.to_raw(),
|
||||||
|
name: dto.name.clone(),
|
||||||
|
created_at: dto.created_at.clone(),
|
||||||
|
updated_at: dto.updated_at.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||||
pub struct PermissionsQueryDto {
|
pub struct PermissionsQueryDto {
|
||||||
pub id: Thing,
|
pub id: Thing,
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ pub enum PermissionsEnum {
|
|||||||
CreateUsers,
|
CreateUsers,
|
||||||
DeleteUsers,
|
DeleteUsers,
|
||||||
UpdateUsers,
|
UpdateUsers,
|
||||||
|
ActivateUsers,
|
||||||
ReadListRoles,
|
ReadListRoles,
|
||||||
ReadDetailRoles,
|
ReadDetailRoles,
|
||||||
CreateRoles,
|
CreateRoles,
|
||||||
@@ -27,6 +28,7 @@ impl fmt::Display for PermissionsEnum {
|
|||||||
PermissionsEnum::CreateUsers => "Create Users",
|
PermissionsEnum::CreateUsers => "Create Users",
|
||||||
PermissionsEnum::DeleteUsers => "Delete Users",
|
PermissionsEnum::DeleteUsers => "Delete Users",
|
||||||
PermissionsEnum::UpdateUsers => "Update Users",
|
PermissionsEnum::UpdateUsers => "Update Users",
|
||||||
|
PermissionsEnum::ActivateUsers => "Activate Users",
|
||||||
PermissionsEnum::ReadListRoles => "Read List Roles",
|
PermissionsEnum::ReadListRoles => "Read List Roles",
|
||||||
PermissionsEnum::ReadDetailRoles => "Read Detail Roles",
|
PermissionsEnum::ReadDetailRoles => "Read Detail Roles",
|
||||||
PermissionsEnum::CreateRoles => "Create Roles",
|
PermissionsEnum::CreateRoles => "Create Roles",
|
||||||
|
|||||||
@@ -1,13 +1,16 @@
|
|||||||
use axum::{
|
use axum::{
|
||||||
|
Extension, Json,
|
||||||
extract::{Path, Query},
|
extract::{Path, Query},
|
||||||
response::IntoResponse,
|
response::IntoResponse,
|
||||||
Extension, Json,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
use super::{RolesItemDto, RolesRequestCreateDto, RolesRequestUpdateDto};
|
use super::{
|
||||||
|
RolesDetailItemDto, RolesListItemDto, RolesRequestCreateDto, RolesRequestUpdateDto,
|
||||||
|
};
|
||||||
use crate::{
|
use crate::{
|
||||||
permissions_guard, v1::roles_service::RolesService, AppState, MessageResponseDto,
|
AppState, MessageResponseDto, MetaRequestDto, PermissionsEnum,
|
||||||
MetaRequestDto, PermissionsEnum, ResponseListSuccessDto, ResponseSuccessDto,
|
ResponseListSuccessDto, ResponseSuccessDto, permissions_guard,
|
||||||
|
v1::roles_service::RolesService,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[utoipa::path(
|
#[utoipa::path(
|
||||||
@@ -26,7 +29,7 @@ use crate::{
|
|||||||
("filter_by" = Option<String>, Query, description = "Field to filter by"),
|
("filter_by" = Option<String>, Query, description = "Field to filter by"),
|
||||||
),
|
),
|
||||||
responses(
|
responses(
|
||||||
(status = 200, description = "Get role list", body = ResponseListSuccessDto<Vec<RolesItemDto>>)
|
(status = 200, description = "Get role list", body = ResponseListSuccessDto<Vec<RolesListItemDto>>)
|
||||||
),
|
),
|
||||||
tag = "Roles"
|
tag = "Roles"
|
||||||
)]
|
)]
|
||||||
@@ -55,7 +58,7 @@ pub async fn get_role_list(
|
|||||||
path = "/v1/roles/detail/{id}",
|
path = "/v1/roles/detail/{id}",
|
||||||
params(("id" = String, Path, description = "Role ID")),
|
params(("id" = String, Path, description = "Role ID")),
|
||||||
responses(
|
responses(
|
||||||
(status = 200, description = "Get role by ID", body = ResponseSuccessDto<RolesItemDto>)
|
(status = 200, description = "Get role by ID", body = ResponseSuccessDto<RolesDetailItemDto>)
|
||||||
),
|
),
|
||||||
tag = "Roles"
|
tag = "Roles"
|
||||||
)]
|
)]
|
||||||
|
|||||||
@@ -5,17 +5,25 @@ use utoipa::ToSchema;
|
|||||||
use validator::Validate;
|
use validator::Validate;
|
||||||
|
|
||||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||||
pub struct RolesRequestDto {
|
pub struct RolesRequestUpdateDto {
|
||||||
|
#[validate(length(min = 1, message = "Role name must not be empty"))]
|
||||||
|
pub name: Option<String>,
|
||||||
|
pub permissions: Option<Vec<String>>,
|
||||||
|
pub overwrite: Option<bool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||||
|
pub struct RolesRequestCreateDto {
|
||||||
#[validate(length(min = 1, message = "Role name must not be empty"))]
|
#[validate(length(min = 1, message = "Role name must not be empty"))]
|
||||||
pub name: String,
|
pub name: String,
|
||||||
pub permissions: Option<Vec<String>>,
|
pub permissions: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||||
pub struct RolesListItemDto {
|
pub struct RolesListItemDto {
|
||||||
pub id: String,
|
pub id: String,
|
||||||
pub name: String,
|
pub name: String,
|
||||||
pub permissions_count: u64,
|
pub permissions_count: usize,
|
||||||
pub created_at: Option<String>,
|
pub created_at: Option<String>,
|
||||||
pub updated_at: Option<String>,
|
pub updated_at: Option<String>,
|
||||||
}
|
}
|
||||||
@@ -24,11 +32,29 @@ pub struct RolesListItemDto {
|
|||||||
pub struct RolesDetailItemDto {
|
pub struct RolesDetailItemDto {
|
||||||
pub id: String,
|
pub id: String,
|
||||||
pub name: String,
|
pub name: String,
|
||||||
|
pub is_deleted: bool,
|
||||||
pub permissions: Vec<PermissionsItemDto>,
|
pub permissions: Vec<PermissionsItemDto>,
|
||||||
pub created_at: Option<String>,
|
pub created_at: Option<String>,
|
||||||
pub updated_at: Option<String>,
|
pub updated_at: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl RolesDetailItemDto {
|
||||||
|
pub fn from(dto: &RolesDetailQueryDto) -> Self {
|
||||||
|
Self {
|
||||||
|
id: dto.id.id.to_raw(),
|
||||||
|
name: dto.name.clone(),
|
||||||
|
is_deleted: dto.is_deleted,
|
||||||
|
permissions: dto
|
||||||
|
.permissions
|
||||||
|
.iter()
|
||||||
|
.map(PermissionsItemDto::from)
|
||||||
|
.collect(),
|
||||||
|
created_at: dto.created_at.clone(),
|
||||||
|
updated_at: dto.updated_at.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||||
pub struct RolesDetailQueryDto {
|
pub struct RolesDetailQueryDto {
|
||||||
pub id: Thing,
|
pub id: Thing,
|
||||||
|
|||||||
@@ -4,8 +4,7 @@ use std::fmt;
|
|||||||
pub enum RolesEnum {
|
pub enum RolesEnum {
|
||||||
Admin,
|
Admin,
|
||||||
User,
|
User,
|
||||||
Student,
|
Staff,
|
||||||
Staf,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl fmt::Display for RolesEnum {
|
impl fmt::Display for RolesEnum {
|
||||||
@@ -13,8 +12,7 @@ impl fmt::Display for RolesEnum {
|
|||||||
let roles_str = match self {
|
let roles_str = match self {
|
||||||
RolesEnum::Admin => "Admin",
|
RolesEnum::Admin => "Admin",
|
||||||
RolesEnum::User => "User",
|
RolesEnum::User => "User",
|
||||||
RolesEnum::Student => "Student",
|
RolesEnum::Staff => "Staff",
|
||||||
RolesEnum::Staf => "Staf",
|
|
||||||
};
|
};
|
||||||
write!(f, "{}", roles_str)
|
write!(f, "{}", roles_str)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,15 @@
|
|||||||
use super::{
|
use super::{
|
||||||
RolesItemByIdDto, RolesItemByIdDtoRaw, RolesItemDto, RolesItemDtoRaw, RolesRequestCreateDto, RolesRequestUpdateDto, RolesSchema
|
RolesDetailItemDto, RolesDetailQueryDto, RolesListItemDto, RolesRequestCreateDto,
|
||||||
|
RolesRequestUpdateDto, RolesSchema,
|
||||||
};
|
};
|
||||||
use crate::{
|
use crate::{
|
||||||
extract_id, get_id, make_thing, query_list_with_meta, AppState, MetaRequestDto,
|
AppState, MetaRequestDto, PermissionsItemDto, ResourceEnum,
|
||||||
PermissionsItemDto, ResourceEnum, ResponseListSuccessDto,
|
ResponseListSuccessDto, extract_id, get_id, make_thing, query_list_with_meta,
|
||||||
};
|
};
|
||||||
use anyhow::{bail, Result};
|
use anyhow::{Result, bail};
|
||||||
use surrealdb::sql::Thing;
|
use imphnen_utils::DetailQueryBuilder;
|
||||||
use surrealdb::Uuid;
|
use surrealdb::Uuid;
|
||||||
|
use surrealdb::sql::Thing;
|
||||||
|
|
||||||
pub struct RolesRepository<'a> {
|
pub struct RolesRepository<'a> {
|
||||||
state: &'a AppState,
|
state: &'a AppState,
|
||||||
@@ -18,74 +20,73 @@ impl<'a> RolesRepository<'a> {
|
|||||||
Self { state }
|
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(
|
pub async fn query_role_list(
|
||||||
&self,
|
&self,
|
||||||
meta: MetaRequestDto,
|
meta: MetaRequestDto,
|
||||||
) -> Result<ResponseListSuccessDto<Vec<RolesItemDto>>> {
|
) -> Result<ResponseListSuccessDto<Vec<RolesListItemDto>>> {
|
||||||
let mut conditions = vec!["is_deleted = false".into()];
|
let mut conditions = vec!["is_deleted = false".into()];
|
||||||
if meta.search.is_some() {
|
if let Some(_search) = meta.search.as_deref().filter(|s| !s.is_empty()) {
|
||||||
conditions.push("string::contains(name, $search)".into());
|
conditions.push("string::contains(name ?? '', $search)".into());
|
||||||
}
|
}
|
||||||
if meta.filter_by.is_some() && meta.filter.is_some() {
|
if let (Some(filter_by), Some(filter_val)) =
|
||||||
let filter_by = meta.filter_by.as_ref().unwrap();
|
(meta.filter_by.as_ref(), meta.filter.as_ref())
|
||||||
conditions.push(format!("{} = $filter", filter_by));
|
{
|
||||||
|
if !filter_val.is_empty() {
|
||||||
|
conditions.push(format!("{} = $filter", filter_by));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
let raw_result: ResponseListSuccessDto<Vec<RolesItemDtoRaw>> = query_list_with_meta(
|
let raw_result: ResponseListSuccessDto<Vec<RolesDetailQueryDto>> =
|
||||||
&self.state.surrealdb_ws,
|
query_list_with_meta(
|
||||||
&ResourceEnum::Roles.to_string(),
|
&self.state.surrealdb_ws,
|
||||||
&meta,
|
&ResourceEnum::Roles.to_string(),
|
||||||
conditions,
|
&meta,
|
||||||
None,
|
conditions,
|
||||||
)
|
None,
|
||||||
.await?;
|
"name",
|
||||||
let transformed_data = raw_result
|
None,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let data = raw_result
|
||||||
.data
|
.data
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|role| {
|
.map(|role| RolesListItemDto {
|
||||||
RolesItemDto {
|
id: extract_id(&role.id),
|
||||||
name: role.name,
|
name: role.name,
|
||||||
created_at: role.created_at,
|
created_at: role.created_at,
|
||||||
updated_at: role.updated_at,
|
updated_at: role.updated_at,
|
||||||
permissions: role.permissions
|
permissions_count: role.permissions.len(),
|
||||||
.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>>();
|
.collect();
|
||||||
let transformed_meta = raw_result.meta;
|
|
||||||
Ok(ResponseListSuccessDto {
|
Ok(ResponseListSuccessDto {
|
||||||
data: transformed_data,
|
data,
|
||||||
meta: transformed_meta,
|
meta: raw_result.meta,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn query_role_by_name(&self, name: String) -> Result<RolesItemByIdDto> {
|
pub async fn query_role_by_name(
|
||||||
|
&self,
|
||||||
|
name: String,
|
||||||
|
) -> Result<RolesDetailItemDto> {
|
||||||
let db = &self.state.surrealdb_ws;
|
let db = &self.state.surrealdb_ws;
|
||||||
let sql = format!(
|
let builder = DetailQueryBuilder::new(ResourceEnum::Roles.to_string())
|
||||||
"SELECT *, permissions FROM {} WHERE name = $name AND is_deleted = false LIMIT 1 FETCH permissions",
|
.with_where("name")
|
||||||
ResourceEnum::Roles.to_string()
|
.where_value(name.clone())
|
||||||
);
|
.with_select_fields(vec![
|
||||||
let mut result = db.query(sql).bind(("name", name.clone())).await?;
|
"id",
|
||||||
let role: Option<RolesItemByIdDtoRaw> = result.take(0)?;
|
"name",
|
||||||
let role = match role {
|
"permissions",
|
||||||
|
"created_at",
|
||||||
|
"updated_at",
|
||||||
|
"is_deleted",
|
||||||
|
])
|
||||||
|
.with_fetch("permissions");
|
||||||
|
|
||||||
|
let sql = builder.build();
|
||||||
|
let result: Option<RolesDetailQueryDto> = builder
|
||||||
|
.apply_bindings(db.query(sql).bind(("name", name)))
|
||||||
|
.await?
|
||||||
|
.take(0)?;
|
||||||
|
let role = match result {
|
||||||
Some(r) if !r.is_deleted => r,
|
Some(r) if !r.is_deleted => r,
|
||||||
_ => bail!("Role not found"),
|
_ => bail!("Role not found"),
|
||||||
};
|
};
|
||||||
@@ -98,8 +99,8 @@ impl<'a> RolesRepository<'a> {
|
|||||||
created_at: perm.created_at,
|
created_at: perm.created_at,
|
||||||
updated_at: perm.updated_at,
|
updated_at: perm.updated_at,
|
||||||
})
|
})
|
||||||
.collect::<Vec<_>>();
|
.collect();
|
||||||
Ok(RolesItemByIdDto {
|
Ok(RolesDetailItemDto {
|
||||||
id: extract_id(&role.id),
|
id: extract_id(&role.id),
|
||||||
name: role.name,
|
name: role.name,
|
||||||
is_deleted: role.is_deleted,
|
is_deleted: role.is_deleted,
|
||||||
@@ -109,16 +110,23 @@ impl<'a> RolesRepository<'a> {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn query_role_by_id(&self, id: String) -> Result<RolesItemByIdDto> {
|
pub async fn query_role_by_id(&self, id: String) -> Result<RolesDetailItemDto> {
|
||||||
let db = &self.state.surrealdb_ws;
|
let db = &self.state.surrealdb_ws;
|
||||||
let query = format!(
|
let builder = DetailQueryBuilder::new(ResourceEnum::Roles.to_string())
|
||||||
"SELECT *, permissions.* AS permissions
|
.with_id(&id)
|
||||||
FROM app_roles:⟨{}⟩ WHERE is_deleted = false FETCH permissions",
|
.with_select_fields(vec![
|
||||||
id
|
"id",
|
||||||
);
|
"name",
|
||||||
let mut result = db.query(query).await?;
|
"is_deleted",
|
||||||
let role: Option<RolesItemByIdDtoRaw> = result.take(0)?;
|
"permissions",
|
||||||
let role = match role {
|
"created_at",
|
||||||
|
"updated_at",
|
||||||
|
])
|
||||||
|
.with_fetch("permissions");
|
||||||
|
let sql = builder.build();
|
||||||
|
let result: Option<RolesDetailQueryDto> =
|
||||||
|
builder.apply_bindings(db.query(sql)).await?.take(0)?;
|
||||||
|
let role = match result {
|
||||||
Some(r) if !r.is_deleted => r,
|
Some(r) if !r.is_deleted => r,
|
||||||
_ => bail!("Role not found"),
|
_ => bail!("Role not found"),
|
||||||
};
|
};
|
||||||
@@ -131,8 +139,8 @@ impl<'a> RolesRepository<'a> {
|
|||||||
created_at: perm.created_at,
|
created_at: perm.created_at,
|
||||||
updated_at: perm.updated_at,
|
updated_at: perm.updated_at,
|
||||||
})
|
})
|
||||||
.collect::<Vec<_>>();
|
.collect();
|
||||||
Ok(RolesItemByIdDto {
|
Ok(RolesDetailItemDto {
|
||||||
id: extract_id(&role.id),
|
id: extract_id(&role.id),
|
||||||
name: role.name,
|
name: role.name,
|
||||||
is_deleted: role.is_deleted,
|
is_deleted: role.is_deleted,
|
||||||
@@ -147,14 +155,12 @@ impl<'a> RolesRepository<'a> {
|
|||||||
payload: RolesRequestCreateDto,
|
payload: RolesRequestCreateDto,
|
||||||
) -> Result<String> {
|
) -> Result<String> {
|
||||||
let db = &self.state.surrealdb_ws;
|
let db = &self.state.surrealdb_ws;
|
||||||
|
|
||||||
let role_id = Uuid::new_v4().to_string();
|
let role_id = Uuid::new_v4().to_string();
|
||||||
let permission_things: Vec<Thing> = payload
|
let permission_things: Vec<Thing> = payload
|
||||||
.permissions
|
.permissions
|
||||||
.iter()
|
.iter()
|
||||||
.map(|id| make_thing(&ResourceEnum::Permissions.to_string(), id))
|
.map(|id| make_thing(&ResourceEnum::Permissions.to_string(), id))
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
let role = RolesSchema {
|
let role = RolesSchema {
|
||||||
id: make_thing(&ResourceEnum::Roles.to_string(), &role_id),
|
id: make_thing(&ResourceEnum::Roles.to_string(), &role_id),
|
||||||
name: payload.name,
|
name: payload.name,
|
||||||
@@ -163,12 +169,10 @@ impl<'a> RolesRepository<'a> {
|
|||||||
created_at: Some(crate::get_iso_date()),
|
created_at: Some(crate::get_iso_date()),
|
||||||
updated_at: Some(crate::get_iso_date()),
|
updated_at: Some(crate::get_iso_date()),
|
||||||
};
|
};
|
||||||
|
|
||||||
let _: Option<RolesSchema> = db
|
let _: Option<RolesSchema> = db
|
||||||
.create((&ResourceEnum::Roles.to_string(), role_id))
|
.create((&ResourceEnum::Roles.to_string(), role_id))
|
||||||
.content(role)
|
.content(role)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
Ok("Role with permissions created successfully".into())
|
Ok("Role with permissions created successfully".into())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -178,31 +182,11 @@ impl<'a> RolesRepository<'a> {
|
|||||||
data: RolesRequestUpdateDto,
|
data: RolesRequestUpdateDto,
|
||||||
) -> Result<String> {
|
) -> Result<String> {
|
||||||
let db = &self.state.surrealdb_ws;
|
let db = &self.state.surrealdb_ws;
|
||||||
let thing_id = make_thing(&ResourceEnum::Roles.to_string(), &id);
|
let existing = self.query_role_by_id(id.clone()).await?;
|
||||||
let existing = self.query_raw_role_by_id(&id).await?;
|
|
||||||
if existing.is_deleted {
|
if existing.is_deleted {
|
||||||
bail!("Role already deleted");
|
bail!("Role already deleted");
|
||||||
}
|
}
|
||||||
let permissions: Vec<Thing> = if let Some(permission_ids) = &data.permissions {
|
let merged = RolesSchema::update(data, id.clone(), existing);
|
||||||
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> =
|
let record: Option<RolesSchema> =
|
||||||
db.update(get_id(&merged.id)?).content(merged).await?;
|
db.update(get_id(&merged.id)?).content(merged).await?;
|
||||||
match record {
|
match record {
|
||||||
|
|||||||
@@ -1,7 +1,12 @@
|
|||||||
|
use super::{
|
||||||
|
RolesDetailItemDto, RolesDetailQueryDto, RolesRequestCreateDto,
|
||||||
|
RolesRequestUpdateDto,
|
||||||
|
};
|
||||||
|
use crate::{ResourceEnum, make_thing};
|
||||||
|
use imphnen_utils::get_iso_date;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use surrealdb::{sql::Thing, Uuid};
|
use std::collections::HashSet;
|
||||||
|
use surrealdb::{Uuid, sql::Thing};
|
||||||
use crate::{make_thing, ResourceEnum};
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||||
pub struct RolesSchema {
|
pub struct RolesSchema {
|
||||||
@@ -31,3 +36,80 @@ impl Default for RolesSchema {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl RolesSchema {
|
||||||
|
pub fn from(dto: RolesDetailQueryDto) -> Self {
|
||||||
|
Self {
|
||||||
|
id: dto.id,
|
||||||
|
name: dto.name,
|
||||||
|
permissions: dto
|
||||||
|
.permissions
|
||||||
|
.into_iter()
|
||||||
|
.map(|perm| {
|
||||||
|
make_thing(&ResourceEnum::Permissions.to_string(), &perm.id.to_raw())
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
is_deleted: dto.is_deleted,
|
||||||
|
created_at: dto.created_at,
|
||||||
|
updated_at: dto.updated_at,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn create(dto: RolesRequestCreateDto) -> Self {
|
||||||
|
let permissions: Vec<Thing> = dto
|
||||||
|
.permissions
|
||||||
|
.into_iter()
|
||||||
|
.map(|id| make_thing(&ResourceEnum::Permissions.to_string(), &id))
|
||||||
|
.collect();
|
||||||
|
Self {
|
||||||
|
id: make_thing(
|
||||||
|
&ResourceEnum::Roles.to_string(),
|
||||||
|
&Uuid::new_v4().to_string(),
|
||||||
|
),
|
||||||
|
name: dto.name,
|
||||||
|
permissions,
|
||||||
|
is_deleted: false,
|
||||||
|
created_at: Some(get_iso_date()),
|
||||||
|
updated_at: Some(get_iso_date()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn update(
|
||||||
|
dto: RolesRequestUpdateDto,
|
||||||
|
id: String,
|
||||||
|
existing: RolesDetailItemDto,
|
||||||
|
) -> Self {
|
||||||
|
let name = dto.name.unwrap_or(existing.name);
|
||||||
|
let permissions: Vec<Thing> =
|
||||||
|
match (dto.permissions, dto.overwrite.unwrap_or(false)) {
|
||||||
|
(Some(new_ids), true) => new_ids
|
||||||
|
.iter()
|
||||||
|
.map(|id| make_thing(&ResourceEnum::Permissions.to_string(), id))
|
||||||
|
.collect(),
|
||||||
|
(Some(new_ids), false) => {
|
||||||
|
let mut all_ids: HashSet<String> =
|
||||||
|
existing.permissions.iter().map(|p| p.id.clone()).collect();
|
||||||
|
for id in new_ids {
|
||||||
|
all_ids.insert(id);
|
||||||
|
}
|
||||||
|
all_ids
|
||||||
|
.into_iter()
|
||||||
|
.map(|id| make_thing(&ResourceEnum::Permissions.to_string(), &id))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
(None, _) => existing
|
||||||
|
.permissions
|
||||||
|
.iter()
|
||||||
|
.map(|p| make_thing(&ResourceEnum::Permissions.to_string(), &p.id))
|
||||||
|
.collect(),
|
||||||
|
};
|
||||||
|
Self {
|
||||||
|
id: make_thing(&ResourceEnum::Roles.to_string(), &id),
|
||||||
|
name,
|
||||||
|
permissions,
|
||||||
|
is_deleted: existing.is_deleted,
|
||||||
|
created_at: existing.created_at,
|
||||||
|
updated_at: Some(get_iso_date()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use super::{RolesRepository, RolesRequestCreateDto, RolesRequestUpdateDto};
|
use super::{RolesRepository, RolesRequestCreateDto, RolesRequestUpdateDto};
|
||||||
use crate::{
|
use crate::{
|
||||||
common_response, success_list_response, success_response, validate_request,
|
|
||||||
AppState, MetaRequestDto, ResponseListSuccessDto, ResponseSuccessDto,
|
AppState, MetaRequestDto, ResponseListSuccessDto, ResponseSuccessDto,
|
||||||
|
common_response, success_list_response, success_response, validate_request,
|
||||||
};
|
};
|
||||||
use axum::{http::StatusCode, response::Response};
|
use axum::{http::StatusCode, response::Response};
|
||||||
|
|
||||||
|
|||||||
@@ -1,16 +1,16 @@
|
|||||||
|
use crate::{AppState, MetaRequestDto, v1::users_service::UsersService};
|
||||||
|
use crate::{
|
||||||
|
MessageResponseDto, PermissionsEnum, ResponseListSuccessDto, ResponseSuccessDto,
|
||||||
|
UsersCreateRequestDto, UsersDetailItemDto, permissions_guard,
|
||||||
|
};
|
||||||
use axum::extract::{Path, Query};
|
use axum::extract::{Path, Query};
|
||||||
use axum::http::HeaderMap;
|
use axum::http::HeaderMap;
|
||||||
use axum::response::IntoResponse;
|
use axum::response::IntoResponse;
|
||||||
use axum::{Extension, Json};
|
use axum::{Extension, Json};
|
||||||
|
|
||||||
use crate::{
|
use super::{
|
||||||
permissions_guard, MessageResponseDto, PermissionsEnum, ResponseListSuccessDto,
|
UsersActiveInactiveRequestDto, UsersListItemDto, UsersUpdateRequestDto,
|
||||||
ResponseSuccessDto, UsersActiveInactiveRequestDto, UsersCreateRequestDto,
|
|
||||||
UsersDetailItemDto,
|
|
||||||
};
|
};
|
||||||
use crate::{v1::users_service::UsersService, AppState, MetaRequestDto};
|
|
||||||
|
|
||||||
use super::{UsersListItemDto, UsersUpdateRequestDto};
|
|
||||||
|
|
||||||
#[utoipa::path(
|
#[utoipa::path(
|
||||||
get,
|
get,
|
||||||
@@ -204,7 +204,7 @@ pub async fn patch_user_active_status(
|
|||||||
match permissions_guard(
|
match permissions_guard(
|
||||||
&headers,
|
&headers,
|
||||||
state.clone(),
|
state.clone(),
|
||||||
vec![PermissionsEnum::UpdateUsers],
|
vec![PermissionsEnum::ActivateUsers],
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::{RolesDetailQueryDto, RolesItemDto};
|
use crate::{RolesDetailItemDto, RolesDetailQueryDto};
|
||||||
use lazy_static::lazy_static;
|
use lazy_static::lazy_static;
|
||||||
use regex::Regex;
|
use regex::Regex;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
@@ -10,6 +10,17 @@ lazy_static! {
|
|||||||
static ref PASSWORD_REGEX: Regex = Regex::new(r"^[A-Za-z\d@$!%*?&]{8,}$").unwrap();
|
static ref PASSWORD_REGEX: Regex = Regex::new(r"^[A-Za-z\d@$!%*?&]{8,}$").unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||||
|
pub struct UsersActiveInactiveRequestDto {
|
||||||
|
pub is_active: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||||
|
pub struct UsersSetNewPasswordRequestDto {
|
||||||
|
pub password: String,
|
||||||
|
pub old_password: String,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||||
pub struct UsersCreateRequestDto {
|
pub struct UsersCreateRequestDto {
|
||||||
#[validate(
|
#[validate(
|
||||||
@@ -71,7 +82,7 @@ pub struct UsersUpdateRequestDto {
|
|||||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||||
pub struct UsersDetailItemDto {
|
pub struct UsersDetailItemDto {
|
||||||
pub id: String,
|
pub id: String,
|
||||||
pub role: RolesItemDto,
|
pub role: RolesDetailItemDto,
|
||||||
pub fullname: String,
|
pub fullname: String,
|
||||||
pub email: String,
|
pub email: String,
|
||||||
pub avatar: Option<String>,
|
pub avatar: Option<String>,
|
||||||
@@ -83,6 +94,24 @@ pub struct UsersDetailItemDto {
|
|||||||
pub updated_at: String,
|
pub updated_at: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl UsersDetailItemDto {
|
||||||
|
pub fn from(dto: UsersDetailQueryDto) -> Self {
|
||||||
|
Self {
|
||||||
|
id: dto.id.id.to_raw(),
|
||||||
|
role: RolesDetailItemDto::from(&dto.role),
|
||||||
|
fullname: dto.fullname,
|
||||||
|
email: dto.email,
|
||||||
|
avatar: dto.avatar,
|
||||||
|
phone_number: dto.phone_number,
|
||||||
|
is_active: dto.is_active,
|
||||||
|
gender: dto.gender,
|
||||||
|
birthdate: dto.birthdate,
|
||||||
|
created_at: dto.created_at,
|
||||||
|
updated_at: dto.updated_at,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||||
pub struct UsersListItemDto {
|
pub struct UsersListItemDto {
|
||||||
pub id: String,
|
pub id: String,
|
||||||
@@ -110,7 +139,7 @@ pub struct UsersListQueryDto {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl UsersListQueryDto {
|
impl UsersListQueryDto {
|
||||||
pub fn list_from(&self, role: String) -> UsersListItemDto {
|
pub fn from(&self, role: String) -> UsersListItemDto {
|
||||||
UsersListItemDto {
|
UsersListItemDto {
|
||||||
id: self.id.id.to_raw(),
|
id: self.id.id.to_raw(),
|
||||||
role,
|
role,
|
||||||
|
|||||||
@@ -1,27 +1,30 @@
|
|||||||
use super::{UsersDetailQueryDto, UsersListItemDto, UsersListQueryDto, UsersSchema};
|
use super::{UsersDetailQueryDto, UsersListItemDto, UsersListQueryDto, UsersSchema};
|
||||||
use crate::{
|
use crate::{
|
||||||
AppState, MetaRequestDto, PermissionsItemDto, PermissionsItemDtoRaw, ResourceEnum,
|
AppState, MetaRequestDto, PermissionsQueryDto, ResourceEnum,
|
||||||
ResponseListSuccessDto, RolesDetailQueryDto, extract_id, get_id, make_thing,
|
ResponseListSuccessDto, RolesDetailQueryDto, get_id, make_thing,
|
||||||
query_list_with_meta,
|
query_list_with_meta,
|
||||||
};
|
};
|
||||||
use anyhow::{Result, bail};
|
use anyhow::{Result, bail};
|
||||||
|
use imphnen_utils::DetailQueryBuilder;
|
||||||
|
use surrealdb::{Surreal, engine::remote::ws::Client};
|
||||||
|
|
||||||
pub struct UsersRepository<'a> {
|
pub struct UsersRepository<'a> {
|
||||||
state: &'a AppState,
|
state: &'a AppState,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn build_user_by_field_query(field: &str) -> String {
|
pub async fn update_partial_schema(
|
||||||
format!(
|
db: &Surreal<Client>,
|
||||||
r#"
|
table: &str,
|
||||||
SELECT *, role AS role
|
id: &str,
|
||||||
FROM {}
|
patch: UsersSchema,
|
||||||
WHERE {} = $value AND is_deleted = false
|
) -> Result<String> {
|
||||||
LIMIT 1
|
let thing = make_thing(table, id);
|
||||||
FETCH role, role.permissions
|
let record_key = get_id(&thing)?;
|
||||||
"#,
|
let result: Option<UsersSchema> = db.update(record_key).merge(patch).await?;
|
||||||
ResourceEnum::Users.to_string(),
|
match result {
|
||||||
field
|
Some(_) => Ok("Success update".into()),
|
||||||
)
|
None => bail!("Failed to update"),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> UsersRepository<'a> {
|
impl<'a> UsersRepository<'a> {
|
||||||
@@ -59,7 +62,7 @@ impl<'a> UsersRepository<'a> {
|
|||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|schema| {
|
.map(|schema| {
|
||||||
let role = schema.clone().role.name;
|
let role = schema.clone().role.name;
|
||||||
schema.list_from(role)
|
schema.from(role)
|
||||||
})
|
})
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
@@ -75,13 +78,31 @@ impl<'a> UsersRepository<'a> {
|
|||||||
) -> Result<UsersDetailQueryDto> {
|
) -> Result<UsersDetailQueryDto> {
|
||||||
let db = &self.state.surrealdb_ws;
|
let db = &self.state.surrealdb_ws;
|
||||||
|
|
||||||
let sql = build_user_by_field_query("email");
|
let builder = DetailQueryBuilder::new(ResourceEnum::Users.to_string())
|
||||||
|
.with_where("email")
|
||||||
|
.where_value(email.clone())
|
||||||
|
.with_select_fields(vec![
|
||||||
|
"id",
|
||||||
|
"fullname",
|
||||||
|
"email",
|
||||||
|
"avatar",
|
||||||
|
"phone_number",
|
||||||
|
"is_active",
|
||||||
|
"is_deleted",
|
||||||
|
"gender",
|
||||||
|
"birthdate",
|
||||||
|
"password",
|
||||||
|
"created_at",
|
||||||
|
"updated_at",
|
||||||
|
"role",
|
||||||
|
])
|
||||||
|
.with_fetch("role")
|
||||||
|
.with_fetch("role.permissions");
|
||||||
|
|
||||||
let user_opt: Option<UsersDetailQueryDto> = db
|
let sql = builder.build();
|
||||||
.query(sql)
|
|
||||||
.bind(("email", email.clone()))
|
let user_opt: Option<UsersDetailQueryDto> =
|
||||||
.await?
|
builder.apply_bindings(db.query(sql)).await?.take(0)?;
|
||||||
.take(0)?;
|
|
||||||
|
|
||||||
let Some(user) = user_opt else {
|
let Some(user) = user_opt else {
|
||||||
bail!("User not found");
|
bail!("User not found");
|
||||||
@@ -95,7 +116,7 @@ impl<'a> UsersRepository<'a> {
|
|||||||
.role
|
.role
|
||||||
.permissions
|
.permissions
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|perm| PermissionsItemDtoRaw {
|
.map(|perm| PermissionsQueryDto {
|
||||||
id: perm.id,
|
id: perm.id,
|
||||||
name: perm.name,
|
name: perm.name,
|
||||||
created_at: perm.created_at,
|
created_at: perm.created_at,
|
||||||
@@ -130,15 +151,32 @@ impl<'a> UsersRepository<'a> {
|
|||||||
pub async fn query_user_by_id(&self, id: String) -> Result<UsersDetailQueryDto> {
|
pub async fn query_user_by_id(&self, id: String) -> Result<UsersDetailQueryDto> {
|
||||||
let db = &self.state.surrealdb_ws;
|
let db = &self.state.surrealdb_ws;
|
||||||
|
|
||||||
let sql = build_user_by_field_query(&make_thing("app_users", &id).to_raw());
|
let builder = DetailQueryBuilder::new(ResourceEnum::Users.to_string())
|
||||||
|
.with_id(&id)
|
||||||
|
.with_select_fields(vec![
|
||||||
|
"id",
|
||||||
|
"fullname",
|
||||||
|
"email",
|
||||||
|
"avatar",
|
||||||
|
"phone_number",
|
||||||
|
"is_active",
|
||||||
|
"is_deleted",
|
||||||
|
"gender",
|
||||||
|
"birthdate",
|
||||||
|
"password",
|
||||||
|
"created_at",
|
||||||
|
"updated_at",
|
||||||
|
"role",
|
||||||
|
])
|
||||||
|
.with_fetch("role")
|
||||||
|
.with_fetch("role.permissions");
|
||||||
|
|
||||||
let user_opt: Option<UsersDetailQueryDto> = db
|
let sql = builder.build();
|
||||||
.query(sql)
|
|
||||||
.bind(("email", make_thing("app_users", &id).to_raw()))
|
|
||||||
.await?
|
|
||||||
.take(0)?;
|
|
||||||
|
|
||||||
let Some(user) = user_opt else {
|
let result: Option<UsersDetailQueryDto> =
|
||||||
|
builder.apply_bindings(db.query(sql)).await?.take(0)?;
|
||||||
|
|
||||||
|
let Some(user) = result else {
|
||||||
bail!("User not found");
|
bail!("User not found");
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -150,7 +188,7 @@ impl<'a> UsersRepository<'a> {
|
|||||||
.role
|
.role
|
||||||
.permissions
|
.permissions
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|perm| PermissionsItemDtoRaw {
|
.map(|perm| PermissionsQueryDto {
|
||||||
id: perm.id,
|
id: perm.id,
|
||||||
name: perm.name,
|
name: perm.name,
|
||||||
created_at: perm.created_at,
|
created_at: perm.created_at,
|
||||||
@@ -201,10 +239,15 @@ impl<'a> UsersRepository<'a> {
|
|||||||
if existing.is_deleted {
|
if existing.is_deleted {
|
||||||
bail!("User already deleted");
|
bail!("User already deleted");
|
||||||
}
|
}
|
||||||
|
let role_thing = if data.role == existing.role.id {
|
||||||
|
existing.role.id
|
||||||
|
} else {
|
||||||
|
data.clone().role
|
||||||
|
};
|
||||||
let merged = UsersSchema {
|
let merged = UsersSchema {
|
||||||
password: existing.password,
|
password: existing.password,
|
||||||
created_at: existing.created_at,
|
created_at: existing.created_at,
|
||||||
role: make_thing("app_roles", &existing.role.id),
|
role: role_thing,
|
||||||
..data.clone()
|
..data.clone()
|
||||||
};
|
};
|
||||||
let record: Option<UsersSchema> = db.update(record_key).merge(merged).await?;
|
let record: Option<UsersSchema> = db.update(record_key).merge(merged).await?;
|
||||||
@@ -214,76 +257,13 @@ impl<'a> UsersRepository<'a> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn query_active_inactive_user(
|
pub async fn query_delete_user(&self, id: String) -> Result<String> {
|
||||||
&self,
|
|
||||||
email: String,
|
|
||||||
data: UsersActiveInactiveSchema,
|
|
||||||
) -> Result<String> {
|
|
||||||
let db = &self.state.surrealdb_ws;
|
let db = &self.state.surrealdb_ws;
|
||||||
let user = self.query_user_by_email(email.clone()).await?;
|
let user = self.query_user_by_id(id).await?;
|
||||||
if user.is_deleted {
|
if user.is_deleted {
|
||||||
bail!("User already deleted");
|
bail!("User already deleted");
|
||||||
}
|
}
|
||||||
let record_key = get_id(&user.id)?;
|
let record_key = get_id(&user.id)?;
|
||||||
let record: Option<UsersSchema> = db
|
|
||||||
.update(record_key)
|
|
||||||
.merge(UsersActiveInactiveSchema {
|
|
||||||
is_active: data.is_active,
|
|
||||||
})
|
|
||||||
.await?;
|
|
||||||
match record {
|
|
||||||
Some(_) => Ok("Success update user".into()),
|
|
||||||
None => bail!("Failed to update user"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn query_active_inactive_user_by_id(
|
|
||||||
&self,
|
|
||||||
id: String,
|
|
||||||
data: UsersActiveInactiveSchema,
|
|
||||||
) -> Result<String> {
|
|
||||||
let db = &self.state.surrealdb_ws;
|
|
||||||
let record: Option<UsersSchema> = db
|
|
||||||
.update((ResourceEnum::Users.to_string(), id))
|
|
||||||
.merge(UsersActiveInactiveSchema {
|
|
||||||
is_active: data.is_active,
|
|
||||||
})
|
|
||||||
.await?;
|
|
||||||
match record {
|
|
||||||
Some(_) => Ok("Success update user".into()),
|
|
||||||
None => bail!("Failed to update user"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn query_update_password_user(
|
|
||||||
&self,
|
|
||||||
email: String,
|
|
||||||
data: UsersSetNewPasswordSchema,
|
|
||||||
) -> Result<String> {
|
|
||||||
let db = &self.state.surrealdb_ws;
|
|
||||||
let user = self.query_user_by_email(email).await?;
|
|
||||||
let record: Option<UsersSetNewPasswordSchema> = db
|
|
||||||
.update((ResourceEnum::Users.to_string(), user.id.id.to_raw()))
|
|
||||||
.merge(UsersSetNewPasswordSchema {
|
|
||||||
password: data.password.clone(),
|
|
||||||
})
|
|
||||||
.await?;
|
|
||||||
dbg!(record.clone());
|
|
||||||
match record {
|
|
||||||
Some(_) => Ok("Success update password user".into()),
|
|
||||||
None => bail!("Failed to update password user"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn query_delete_user(&self, id: String) -> Result<String> {
|
|
||||||
let db = &self.state.surrealdb_ws;
|
|
||||||
let user_id = make_thing(&ResourceEnum::Users.to_string(), &id);
|
|
||||||
let user = self.query_user_by_id(user_id.id.to_raw()).await?;
|
|
||||||
if user.is_deleted {
|
|
||||||
bail!("User already deleted");
|
|
||||||
}
|
|
||||||
let id = make_thing(&ResourceEnum::Users.to_string(), &user.id);
|
|
||||||
let record_key = get_id(&id)?;
|
|
||||||
let record: Option<UsersSchema> = db
|
let record: Option<UsersSchema> = db
|
||||||
.update(record_key)
|
.update(record_key)
|
||||||
.merge(serde_json::json!({ "is_deleted": true }))
|
.merge(serde_json::json!({ "is_deleted": true }))
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
use super::{UsersDetailItemDto, UsersListItemDto};
|
use super::{UsersCreateRequestDto, UsersDetailQueryDto, UsersUpdateRequestDto};
|
||||||
use crate::RolesItemDto;
|
use imphnen_libs::{ResourceEnum, hash_password};
|
||||||
use imphnen_utils::Crud;
|
use imphnen_utils::{get_iso_date, make_thing};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use surrealdb::sql::Thing;
|
use surrealdb::{Uuid, sql::Thing};
|
||||||
|
|
||||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||||
pub struct UsersSchema {
|
pub struct UsersSchema {
|
||||||
@@ -21,46 +21,89 @@ pub struct UsersSchema {
|
|||||||
pub updated_at: String,
|
pub updated_at: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Crud<UsersListItemDto, String> for UsersSchema {
|
impl Default for UsersSchema {
|
||||||
fn list(&self, role: String) -> UsersListItemDto {
|
fn default() -> Self {
|
||||||
UsersListItemDto {
|
Self {
|
||||||
id: self.id.id.to_raw(),
|
id: Thing::from(("app_users", "dummy")),
|
||||||
role,
|
fullname: "".into(),
|
||||||
fullname: self.fullname.clone(),
|
email: "".into(),
|
||||||
email: self.email.clone(),
|
password: "".into(),
|
||||||
avatar: self.avatar.clone(),
|
avatar: None,
|
||||||
phone_number: self.phone_number.clone(),
|
phone_number: "".into(),
|
||||||
is_active: self.is_active,
|
is_active: false,
|
||||||
created_at: self.created_at.clone(),
|
is_deleted: false,
|
||||||
updated_at: self.updated_at.clone(),
|
gender: None,
|
||||||
}
|
birthdate: None,
|
||||||
}
|
role: Thing::from(("app_roles", "dummy")),
|
||||||
}
|
created_at: "".into(),
|
||||||
|
updated_at: "".into(),
|
||||||
impl Crud<UsersDetailItemDto, RolesItemDto> for UsersSchema {
|
|
||||||
fn detail(&self, role: RolesItemDto) -> UsersDetailItemDto {
|
|
||||||
UsersDetailItemDto {
|
|
||||||
id: self.id.id.to_raw(),
|
|
||||||
role,
|
|
||||||
fullname: self.fullname.clone(),
|
|
||||||
email: self.email.clone(),
|
|
||||||
avatar: self.avatar.clone(),
|
|
||||||
phone_number: self.phone_number.clone(),
|
|
||||||
is_active: self.is_active,
|
|
||||||
gender: self.gender.clone(),
|
|
||||||
birthdate: self.birthdate.clone(),
|
|
||||||
created_at: self.created_at.clone(),
|
|
||||||
updated_at: self.updated_at.clone(),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl UsersSchema {
|
impl UsersSchema {
|
||||||
pub fn list_from(&self, role: String) -> UsersListItemDto {
|
pub fn from(dto: UsersDetailQueryDto) -> Self {
|
||||||
self.list(role)
|
Self {
|
||||||
|
id: dto.id,
|
||||||
|
fullname: dto.fullname,
|
||||||
|
email: dto.email,
|
||||||
|
avatar: dto.avatar,
|
||||||
|
phone_number: dto.phone_number,
|
||||||
|
is_active: dto.is_active,
|
||||||
|
is_deleted: dto.is_deleted,
|
||||||
|
gender: dto.gender,
|
||||||
|
birthdate: dto.birthdate,
|
||||||
|
password: dto.password,
|
||||||
|
created_at: dto.created_at,
|
||||||
|
updated_at: dto.updated_at,
|
||||||
|
role: make_thing(&ResourceEnum::Roles.to_string(), &dto.role.id.to_string()),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn detail_from(&self, role: RolesItemDto) -> UsersDetailItemDto {
|
pub fn update(user: UsersUpdateRequestDto, id: String) -> Self {
|
||||||
self.detail(role)
|
Self {
|
||||||
|
id: make_thing(&ResourceEnum::Users.to_string(), &id),
|
||||||
|
fullname: user.fullname,
|
||||||
|
email: user.email,
|
||||||
|
phone_number: user.phone_number,
|
||||||
|
is_active: user.is_active,
|
||||||
|
gender: user.gender,
|
||||||
|
birthdate: user.birthdate,
|
||||||
|
avatar: user.avatar,
|
||||||
|
is_deleted: false,
|
||||||
|
role: make_thing(&ResourceEnum::Roles.to_string(), &user.role_id),
|
||||||
|
updated_at: get_iso_date(),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn create(user: UsersCreateRequestDto) -> Self {
|
||||||
|
let password = hash_password(&user.password).unwrap();
|
||||||
|
Self {
|
||||||
|
id: make_thing(
|
||||||
|
&ResourceEnum::Users.to_string(),
|
||||||
|
&Uuid::new_v4().to_string(),
|
||||||
|
),
|
||||||
|
fullname: user.fullname,
|
||||||
|
email: user.email,
|
||||||
|
password,
|
||||||
|
phone_number: user.phone_number,
|
||||||
|
is_active: false,
|
||||||
|
gender: None,
|
||||||
|
birthdate: None,
|
||||||
|
avatar: None,
|
||||||
|
is_deleted: false,
|
||||||
|
role: make_thing(&ResourceEnum::Roles.to_string(), &user.role_id),
|
||||||
|
created_at: get_iso_date(),
|
||||||
|
updated_at: get_iso_date(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn patch_password(dto: UsersDetailQueryDto, password: String) -> Self {
|
||||||
|
Self {
|
||||||
|
password,
|
||||||
|
id: dto.id.clone(),
|
||||||
|
..Self::from(dto)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,19 +1,17 @@
|
|||||||
use crate::{
|
use super::{
|
||||||
common_response, extract_email, get_iso_date, hash_password, make_thing,
|
UsersActiveInactiveRequestDto, UsersCreateRequestDto, UsersDetailItemDto,
|
||||||
success_list_response, success_response, validate_request, ResourceEnum,
|
UsersSetNewPasswordRequestDto, UsersUpdateRequestDto,
|
||||||
ResponseSuccessDto,
|
|
||||||
};
|
};
|
||||||
use crate::{
|
use crate::{
|
||||||
AppState, MetaRequestDto, ResponseListSuccessDto, UsersActiveInactiveSchema,
|
AppState, MetaRequestDto, ResponseListSuccessDto, UsersRepository, UsersSchema,
|
||||||
UsersRepository, UsersSchema, UsersSetNewPasswordSchema,
|
};
|
||||||
|
use crate::{
|
||||||
|
ResourceEnum, ResponseSuccessDto, common_response, extract_email, make_thing,
|
||||||
|
success_list_response, success_response, validate_request,
|
||||||
};
|
};
|
||||||
use axum::http::HeaderMap;
|
use axum::http::HeaderMap;
|
||||||
use axum::{http::StatusCode, response::Response};
|
use axum::{http::StatusCode, response::Response};
|
||||||
|
use imphnen_libs::{hash_password, verify_password};
|
||||||
use super::{
|
|
||||||
UsersActiveInactiveRequestDto, UsersCreateRequestDto, UsersDetailItemDto,
|
|
||||||
UsersUpdateRequestDto,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub struct UsersService;
|
pub struct UsersService;
|
||||||
|
|
||||||
@@ -36,17 +34,7 @@ impl UsersService {
|
|||||||
let repo = UsersRepository::new(state);
|
let repo = UsersRepository::new(state);
|
||||||
match repo.query_user_by_id(id).await {
|
match repo.query_user_by_id(id).await {
|
||||||
Ok(user) if !user.is_deleted => success_response(ResponseSuccessDto {
|
Ok(user) if !user.is_deleted => success_response(ResponseSuccessDto {
|
||||||
data: UsersDetailItemDto {
|
data: UsersDetailItemDto::from(user),
|
||||||
id: user.id,
|
|
||||||
role: user.role,
|
|
||||||
fullname: user.fullname,
|
|
||||||
email: user.email,
|
|
||||||
avatar: user.avatar,
|
|
||||||
phone_number: user.phone_number,
|
|
||||||
is_active: user.is_active,
|
|
||||||
gender: user.gender,
|
|
||||||
birthdate: user.birthdate,
|
|
||||||
},
|
|
||||||
}),
|
}),
|
||||||
Ok(_) => common_response(StatusCode::NOT_FOUND, "User not found"),
|
Ok(_) => common_response(StatusCode::NOT_FOUND, "User not found"),
|
||||||
Err(e) => common_response(StatusCode::NOT_FOUND, &e.to_string()),
|
Err(e) => common_response(StatusCode::NOT_FOUND, &e.to_string()),
|
||||||
@@ -55,22 +43,15 @@ impl UsersService {
|
|||||||
|
|
||||||
pub async fn get_user_me(headers: HeaderMap, state: &AppState) -> Response {
|
pub async fn get_user_me(headers: HeaderMap, state: &AppState) -> Response {
|
||||||
let repo = UsersRepository::new(state);
|
let repo = UsersRepository::new(state);
|
||||||
let email = extract_email(&headers).unwrap();
|
let email = match extract_email(&headers) {
|
||||||
let user = repo.query_user_by_email(email).await.unwrap();
|
Some(email) => email,
|
||||||
match repo.query_user_by_id(user.id.id.to_raw()).await {
|
None => return common_response(StatusCode::UNAUTHORIZED, "Invalid token"),
|
||||||
Ok(user) => success_response(ResponseSuccessDto {
|
};
|
||||||
data: UsersDetailItemDto {
|
match repo.query_user_by_email(email).await {
|
||||||
id: user.id,
|
Ok(user) if !user.is_deleted => success_response(ResponseSuccessDto {
|
||||||
role: user.role,
|
data: UsersDetailItemDto::from(user),
|
||||||
fullname: user.fullname,
|
|
||||||
email: user.email,
|
|
||||||
avatar: user.avatar,
|
|
||||||
phone_number: user.phone_number,
|
|
||||||
is_active: user.is_active,
|
|
||||||
gender: user.gender,
|
|
||||||
birthdate: user.birthdate,
|
|
||||||
},
|
|
||||||
}),
|
}),
|
||||||
|
Ok(_) => common_response(StatusCode::NOT_FOUND, "User not found"),
|
||||||
Err(e) => common_response(StatusCode::NOT_FOUND, &e.to_string()),
|
Err(e) => common_response(StatusCode::NOT_FOUND, &e.to_string()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -90,19 +71,7 @@ impl UsersService {
|
|||||||
{
|
{
|
||||||
return common_response(StatusCode::BAD_REQUEST, "User already exists");
|
return common_response(StatusCode::BAD_REQUEST, "User already exists");
|
||||||
}
|
}
|
||||||
let role_thing = make_thing(&ResourceEnum::Roles.to_string(), &new_user.role_id);
|
match repo.query_create_user(UsersSchema::create(new_user)).await {
|
||||||
match repo
|
|
||||||
.query_create_user(UsersSchema {
|
|
||||||
email: new_user.email.clone(),
|
|
||||||
fullname: new_user.fullname.clone(),
|
|
||||||
password: hash_password(&new_user.password).unwrap(),
|
|
||||||
phone_number: new_user.phone_number.clone(),
|
|
||||||
is_active: new_user.is_active.clone(),
|
|
||||||
role: role_thing,
|
|
||||||
..Default::default()
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
Ok(msg) => common_response(StatusCode::CREATED, &msg),
|
Ok(msg) => common_response(StatusCode::CREATED, &msg),
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
common_response(StatusCode::INTERNAL_SERVER_ERROR, &err.to_string())
|
common_response(StatusCode::INTERNAL_SERVER_ERROR, &err.to_string())
|
||||||
@@ -116,28 +85,10 @@ impl UsersService {
|
|||||||
user: UsersUpdateRequestDto,
|
user: UsersUpdateRequestDto,
|
||||||
) -> Response {
|
) -> Response {
|
||||||
let repo = UsersRepository::new(state);
|
let repo = UsersRepository::new(state);
|
||||||
|
|
||||||
if let Err((status, message)) = validate_request(&user) {
|
if let Err((status, message)) = validate_request(&user) {
|
||||||
return common_response(status, &message);
|
return common_response(status, &message);
|
||||||
}
|
}
|
||||||
|
let updated_user = UsersSchema::update(user, id);
|
||||||
let user_id = make_thing(&ResourceEnum::Users.to_string(), &id);
|
|
||||||
let role_id = make_thing(&ResourceEnum::Roles.to_string(), "");
|
|
||||||
|
|
||||||
let updated_user = UsersSchema {
|
|
||||||
id: user_id,
|
|
||||||
fullname: user.fullname,
|
|
||||||
email: user.email,
|
|
||||||
phone_number: user.phone_number,
|
|
||||||
is_active: user.is_active,
|
|
||||||
gender: user.gender,
|
|
||||||
birthdate: user.birthdate,
|
|
||||||
avatar: user.avatar,
|
|
||||||
role: role_id,
|
|
||||||
updated_at: get_iso_date(),
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
|
|
||||||
match repo.query_update_user(updated_user).await {
|
match repo.query_update_user(updated_user).await {
|
||||||
Ok(msg) => common_response(StatusCode::OK, &msg),
|
Ok(msg) => common_response(StatusCode::OK, &msg),
|
||||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||||
@@ -150,30 +101,18 @@ impl UsersService {
|
|||||||
user: UsersUpdateRequestDto,
|
user: UsersUpdateRequestDto,
|
||||||
) -> Response {
|
) -> Response {
|
||||||
let repo = UsersRepository::new(state);
|
let repo = UsersRepository::new(state);
|
||||||
let email = extract_email(&headers).unwrap();
|
let email = match extract_email(&headers) {
|
||||||
let user_data = repo.query_user_by_email(email).await.unwrap();
|
Some(email) => email,
|
||||||
|
None => return common_response(StatusCode::UNAUTHORIZED, "Unauthorized"),
|
||||||
|
};
|
||||||
|
let user_data = match repo.query_user_by_email(email.clone()).await {
|
||||||
|
Ok(user) => user,
|
||||||
|
Err(_) => return common_response(StatusCode::NOT_FOUND, "User not found"),
|
||||||
|
};
|
||||||
if let Err((status, message)) = validate_request(&user) {
|
if let Err((status, message)) = validate_request(&user) {
|
||||||
return common_response(status, &message);
|
return common_response(status, &message);
|
||||||
}
|
}
|
||||||
let user_id =
|
let updated_user = UsersSchema::update(user, user_data.id.id.to_raw());
|
||||||
make_thing(&ResourceEnum::Users.to_string(), &user_data.id.id.to_raw());
|
|
||||||
let role_id = make_thing(&ResourceEnum::Roles.to_string(), "");
|
|
||||||
let updated_user = UsersSchema {
|
|
||||||
id: user_id,
|
|
||||||
fullname: user.fullname,
|
|
||||||
email: user.email,
|
|
||||||
phone_number: user.phone_number,
|
|
||||||
|
|
||||||
is_active: user.is_active,
|
|
||||||
|
|
||||||
gender: user.gender,
|
|
||||||
birthdate: user.birthdate,
|
|
||||||
avatar: user.avatar,
|
|
||||||
|
|
||||||
role: role_id,
|
|
||||||
updated_at: get_iso_date(),
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
match repo.query_update_user(updated_user).await {
|
match repo.query_update_user(updated_user).await {
|
||||||
Ok(msg) => common_response(StatusCode::OK, &msg),
|
Ok(msg) => common_response(StatusCode::OK, &msg),
|
||||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||||
@@ -183,23 +122,23 @@ impl UsersService {
|
|||||||
pub async fn set_user_active_status(
|
pub async fn set_user_active_status(
|
||||||
state: &AppState,
|
state: &AppState,
|
||||||
id: String,
|
id: String,
|
||||||
status: UsersActiveInactiveRequestDto,
|
payload: UsersActiveInactiveRequestDto,
|
||||||
) -> Response {
|
) -> Response {
|
||||||
let repo = UsersRepository::new(state);
|
let repo = UsersRepository::new(state);
|
||||||
let thing_id = make_thing(&ResourceEnum::Users.to_string(), &id);
|
let thing_id = make_thing(&ResourceEnum::Users.to_string(), &id);
|
||||||
match repo.query_user_by_id(thing_id.id.to_raw()).await {
|
match repo.query_user_by_id(thing_id.id.to_raw()).await {
|
||||||
Ok(_) => match repo
|
Ok(user) if !user.is_deleted => {
|
||||||
.query_active_inactive_user_by_id(
|
let patch = UsersSchema {
|
||||||
id,
|
id: user.id.clone(),
|
||||||
UsersActiveInactiveSchema {
|
is_active: payload.is_active,
|
||||||
is_active: status.is_active,
|
..UsersSchema::from(user)
|
||||||
},
|
};
|
||||||
)
|
match repo.query_update_user(patch).await {
|
||||||
.await
|
Ok(msg) => common_response(StatusCode::OK, &msg),
|
||||||
{
|
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||||
Ok(msg) => common_response(StatusCode::OK, &msg),
|
}
|
||||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
}
|
||||||
},
|
Ok(_) => common_response(StatusCode::NOT_FOUND, "User not found"),
|
||||||
Err(err) => common_response(StatusCode::BAD_REQUEST, &err.to_string()),
|
Err(err) => common_response(StatusCode::BAD_REQUEST, &err.to_string()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -207,10 +146,41 @@ impl UsersService {
|
|||||||
pub async fn update_user_password(
|
pub async fn update_user_password(
|
||||||
state: &AppState,
|
state: &AppState,
|
||||||
email: String,
|
email: String,
|
||||||
new_password: UsersSetNewPasswordSchema,
|
payload: UsersSetNewPasswordRequestDto,
|
||||||
) -> Response {
|
) -> Response {
|
||||||
let repo = UsersRepository::new(state);
|
let repo = UsersRepository::new(state);
|
||||||
match repo.query_update_password_user(email, new_password).await {
|
let user = match repo.query_user_by_email(email.clone()).await {
|
||||||
|
Ok(user) if !user.is_deleted => user,
|
||||||
|
_ => return common_response(StatusCode::NOT_FOUND, "User not found"),
|
||||||
|
};
|
||||||
|
let verify_result = match verify_password(&payload.old_password, &user.password)
|
||||||
|
{
|
||||||
|
Ok(result) => result,
|
||||||
|
Err(_) => {
|
||||||
|
return common_response(
|
||||||
|
StatusCode::BAD_REQUEST,
|
||||||
|
"Old password is incorrect",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if !verify_result {
|
||||||
|
return common_response(StatusCode::BAD_REQUEST, "Old password is incorrect");
|
||||||
|
}
|
||||||
|
let new_password = match hash_password(&payload.password) {
|
||||||
|
Ok(pw) => pw,
|
||||||
|
Err(_) => {
|
||||||
|
return common_response(
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
"Failed to hash password",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let patch = UsersSchema {
|
||||||
|
id: user.id.clone(),
|
||||||
|
password: new_password,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
match repo.query_update_user(patch).await {
|
||||||
Ok(msg) => common_response(StatusCode::OK, &msg),
|
Ok(msg) => common_response(StatusCode::OK, &msg),
|
||||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,3 +3,7 @@ use surrealdb::sql::Thing;
|
|||||||
pub fn make_thing(table: &str, id: &str) -> Thing {
|
pub fn make_thing(table: &str, id: &str) -> Thing {
|
||||||
Thing::from((table, id))
|
Thing::from((table, id))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn make_thing_str(table: &str, id: &str) -> String {
|
||||||
|
format!("{}:⟨{}⟩", table, id)
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
use imphnen_libs::MetaRequestDto;
|
use imphnen_libs::MetaRequestDto;
|
||||||
|
use surrealdb::engine::remote::ws::Client;
|
||||||
|
use surrealdb::method::Query;
|
||||||
|
use surrealdb::sql::Thing;
|
||||||
|
|
||||||
pub struct ListQueryBuilder {
|
pub struct ListQueryBuilder {
|
||||||
resource: String,
|
resource: String,
|
||||||
@@ -135,3 +138,106 @@ impl ListQueryBuilder {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub struct DetailQueryBuilder {
|
||||||
|
resource: String,
|
||||||
|
id: Option<String>,
|
||||||
|
thing: Option<String>,
|
||||||
|
where_field: Option<String>,
|
||||||
|
where_value: Option<String>,
|
||||||
|
select_fields: Vec<String>,
|
||||||
|
fetch_fields: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DetailQueryBuilder {
|
||||||
|
pub fn new(resource: impl Into<String>) -> Self {
|
||||||
|
Self {
|
||||||
|
resource: resource.into(),
|
||||||
|
id: None,
|
||||||
|
thing: None,
|
||||||
|
where_field: None,
|
||||||
|
where_value: None,
|
||||||
|
select_fields: vec![],
|
||||||
|
fetch_fields: vec![],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with_id(mut self, id: impl Into<String>) -> Self {
|
||||||
|
if self.where_field.is_some() || self.thing.is_some() {
|
||||||
|
panic!("Cannot use with_id() after with_where() or with_thing()");
|
||||||
|
}
|
||||||
|
self.id = Some(id.into());
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with_thing(mut self, thing: &Thing) -> Self {
|
||||||
|
if self.id.is_some() || self.where_field.is_some() {
|
||||||
|
panic!("Cannot use with_thing() after with_id() or with_where()");
|
||||||
|
}
|
||||||
|
self.thing = Some(thing.to_string()); // app_users:uuid
|
||||||
|
self.resource = thing.tb.clone(); // update resource dari thing
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with_where(mut self, field: impl Into<String>) -> Self {
|
||||||
|
if self.id.is_some() || self.thing.is_some() {
|
||||||
|
panic!("Cannot use with_where() after with_id() or with_thing()");
|
||||||
|
}
|
||||||
|
self.where_field = Some(field.into());
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn where_value(mut self, value: impl Into<String>) -> Self {
|
||||||
|
self.where_value = Some(value.into());
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with_select_fields(mut self, fields: Vec<&str>) -> Self {
|
||||||
|
self.select_fields = fields.into_iter().map(String::from).collect();
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with_fetch(mut self, field: impl Into<String>) -> Self {
|
||||||
|
self.fetch_fields.push(field.into());
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn build(&self) -> String {
|
||||||
|
let select_clause = if self.select_fields.is_empty() {
|
||||||
|
"*".to_string()
|
||||||
|
} else {
|
||||||
|
self.select_fields.join(", ")
|
||||||
|
};
|
||||||
|
|
||||||
|
let fetch_clause = if self.fetch_fields.is_empty() {
|
||||||
|
String::new()
|
||||||
|
} else {
|
||||||
|
format!("FETCH {}", self.fetch_fields.join(", "))
|
||||||
|
};
|
||||||
|
|
||||||
|
let from_clause = if let Some(thing) = &self.thing {
|
||||||
|
thing.to_string()
|
||||||
|
} else if let Some(id) = &self.id {
|
||||||
|
format!("{}:⟨{}⟩", self.resource, id)
|
||||||
|
} else if let (Some(field), Some(_)) = (&self.where_field, &self.where_value) {
|
||||||
|
format!("{} WHERE {} = $value", self.resource, field)
|
||||||
|
} else {
|
||||||
|
panic!(
|
||||||
|
"You must set one of with_id(), with_thing(), or with_where()+where_value()"
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
format!(
|
||||||
|
"SELECT {} FROM {} {}",
|
||||||
|
select_clause, from_clause, fetch_clause
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn apply_bindings<'q>(&self, query: Query<'q, Client>) -> Query<'q, Client> {
|
||||||
|
if let (Some(_), Some(value)) = (&self.where_field, &self.where_value) {
|
||||||
|
query.bind(("value", value.clone()))
|
||||||
|
} else {
|
||||||
|
query
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user