feat: rename + delete vocabularies, blocked when in use (#30)
This commit is contained in:
@@ -355,12 +355,119 @@ pub(crate) async fn delete_term(
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, ToSchema)]
|
||||
pub(crate) struct RenameVocabularyRequest {
|
||||
pub key: String,
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
patch, path = "/api/admin/vocabularies/{id}",
|
||||
request_body = RenameVocabularyRequest,
|
||||
params(("id" = String, Path, description = "Vocabulary id (UUID)")),
|
||||
responses(
|
||||
(status = 204),
|
||||
(status = 401),
|
||||
(status = 403),
|
||||
(status = 404),
|
||||
(status = 409, description = "Key already in use")
|
||||
)
|
||||
)]
|
||||
pub(crate) async fn rename_vocabulary(
|
||||
auth: Authorized<EditCatalogue>,
|
||||
State(state): State<AppState>,
|
||||
Path(id): Path<String>,
|
||||
Json(req): Json<RenameVocabularyRequest>,
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
let id = id
|
||||
.parse::<VocabularyId>()
|
||||
.map_err(|_| StatusCode::NOT_FOUND)?;
|
||||
|
||||
let mut tx = state
|
||||
.db
|
||||
.pool()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
let existed = db::vocab::rename_vocabulary(
|
||||
&mut tx,
|
||||
AuditActor::User(auth.user.id.to_uuid()),
|
||||
id,
|
||||
&req.key,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
if err.as_database_error().and_then(|e| e.code()).as_deref() == Some("23505") {
|
||||
StatusCode::CONFLICT
|
||||
} else {
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
}
|
||||
})?;
|
||||
|
||||
if existed {
|
||||
tx.commit()
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
} else {
|
||||
Err(StatusCode::NOT_FOUND)
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
delete, path = "/api/admin/vocabularies/{id}",
|
||||
params(("id" = String, Path, description = "Vocabulary id (UUID)")),
|
||||
responses(
|
||||
(status = 204),
|
||||
(status = 401),
|
||||
(status = 403),
|
||||
(status = 404),
|
||||
(status = 409, body = InUseView, description = "Has terms or is bound by a field")
|
||||
)
|
||||
)]
|
||||
pub(crate) async fn delete_vocabulary(
|
||||
auth: Authorized<EditCatalogue>,
|
||||
State(state): State<AppState>,
|
||||
Path(id): Path<String>,
|
||||
) -> Response {
|
||||
let Ok(id) = id.parse::<VocabularyId>() else {
|
||||
return StatusCode::NOT_FOUND.into_response();
|
||||
};
|
||||
|
||||
let Ok(mut tx) = state.db.pool().begin().await else {
|
||||
return StatusCode::INTERNAL_SERVER_ERROR.into_response();
|
||||
};
|
||||
|
||||
match db::vocab::delete_vocabulary(&mut tx, AuditActor::User(auth.user.id.to_uuid()), id).await
|
||||
{
|
||||
Ok(db::DeleteOutcome::Deleted) => match tx.commit().await {
|
||||
Ok(()) => StatusCode::NO_CONTENT.into_response(),
|
||||
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||
},
|
||||
Ok(db::DeleteOutcome::InUse { count }) => {
|
||||
let _ = tx.rollback().await;
|
||||
|
||||
(StatusCode::CONFLICT, Json(InUseView { count })).into_response()
|
||||
}
|
||||
Ok(db::DeleteOutcome::NotFound) => {
|
||||
let _ = tx.rollback().await;
|
||||
|
||||
StatusCode::NOT_FOUND.into_response()
|
||||
}
|
||||
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn routes() -> Router<AppState> {
|
||||
Router::new()
|
||||
.route(
|
||||
"/api/admin/vocabularies",
|
||||
get(list_vocabularies).post(create_vocabulary),
|
||||
)
|
||||
.route(
|
||||
"/api/admin/vocabularies/{id}",
|
||||
axum::routing::patch(rename_vocabulary).delete(delete_vocabulary),
|
||||
)
|
||||
.route(
|
||||
"/api/admin/vocabularies/{id}/terms",
|
||||
get(list_terms).post(add_term),
|
||||
|
||||
@@ -33,6 +33,8 @@ use crate::{
|
||||
admin_vocab::add_term,
|
||||
admin_vocab::update_term,
|
||||
admin_vocab::delete_term,
|
||||
admin_vocab::rename_vocabulary,
|
||||
admin_vocab::delete_vocabulary,
|
||||
admin_search::search_objects,
|
||||
admin_authorities::list_authorities,
|
||||
admin_authorities::create_authority
|
||||
@@ -64,6 +66,7 @@ use crate::{
|
||||
admin_vocab::CreatedId,
|
||||
admin_vocab::UpdateTermRequest,
|
||||
admin_vocab::InUseView,
|
||||
admin_vocab::RenameVocabularyRequest,
|
||||
admin_search::SearchHitView,
|
||||
admin_search::SearchResultsView,
|
||||
admin_authorities::AuthorityView,
|
||||
|
||||
@@ -459,3 +459,131 @@ async fn term_edit_delete_requires_auth(pool: PgPool) {
|
||||
.unwrap();
|
||||
assert_eq!(delete_resp.status(), StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "../db/migrations")]
|
||||
async fn vocabulary_edit_delete_requires_auth(pool: PgPool) {
|
||||
migrate_sessions(&db::Db::from_pool(pool.clone()))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let app = build_app(state(pool));
|
||||
let vocab_uri = "/api/admin/vocabularies/00000000-0000-0000-0000-000000000000";
|
||||
|
||||
let patch_resp = app
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("PATCH")
|
||||
.uri(vocab_uri)
|
||||
.header(header::CONTENT_TYPE, "application/json")
|
||||
.body(Body::from(r#"{"key":"x"}"#))
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(patch_resp.status(), StatusCode::UNAUTHORIZED);
|
||||
|
||||
let delete_resp = app
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("DELETE")
|
||||
.uri(vocab_uri)
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(delete_resp.status(), StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "../db/migrations")]
|
||||
async fn rename_and_delete_vocabulary(pool: PgPool) {
|
||||
migrate_sessions(&db::Db::from_pool(pool.clone()))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
seed_user(&pool, "ed@example.com", "pw-editor-123", Role::Editor).await;
|
||||
|
||||
let app = build_app(state(pool));
|
||||
let cookie = login(&app, "ed@example.com", "pw-editor-123").await;
|
||||
|
||||
let v = send(
|
||||
&app,
|
||||
&cookie,
|
||||
"POST",
|
||||
"/api/admin/vocabularies",
|
||||
Some(r#"{"key":"old"}"#),
|
||||
)
|
||||
.await;
|
||||
let vid: serde_json::Value =
|
||||
serde_json::from_slice(&v.into_body().collect().await.unwrap().to_bytes()).unwrap();
|
||||
let vid = vid["id"].as_str().unwrap().to_owned();
|
||||
|
||||
let renamed = send(
|
||||
&app,
|
||||
&cookie,
|
||||
"PATCH",
|
||||
&format!("/api/admin/vocabularies/{vid}"),
|
||||
Some(r#"{"key":"new"}"#),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(renamed.status(), StatusCode::NO_CONTENT);
|
||||
|
||||
let deleted = send(
|
||||
&app,
|
||||
&cookie,
|
||||
"DELETE",
|
||||
&format!("/api/admin/vocabularies/{vid}"),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(deleted.status(), StatusCode::NO_CONTENT);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "../db/migrations")]
|
||||
async fn delete_vocabulary_with_terms_is_409(pool: PgPool) {
|
||||
migrate_sessions(&db::Db::from_pool(pool.clone()))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
seed_user(&pool, "ed@example.com", "pw-editor-123", Role::Editor).await;
|
||||
|
||||
let app = build_app(state(pool));
|
||||
let cookie = login(&app, "ed@example.com", "pw-editor-123").await;
|
||||
|
||||
let v = send(
|
||||
&app,
|
||||
&cookie,
|
||||
"POST",
|
||||
"/api/admin/vocabularies",
|
||||
Some(r#"{"key":"material"}"#),
|
||||
)
|
||||
.await;
|
||||
let vid: serde_json::Value =
|
||||
serde_json::from_slice(&v.into_body().collect().await.unwrap().to_bytes()).unwrap();
|
||||
let vid = vid["id"].as_str().unwrap().to_owned();
|
||||
|
||||
send(
|
||||
&app,
|
||||
&cookie,
|
||||
"POST",
|
||||
&format!("/api/admin/vocabularies/{vid}/terms"),
|
||||
Some(r#"{"external_uri":null,"labels":[{"lang":"sv","label":"Trä"}]}"#),
|
||||
)
|
||||
.await;
|
||||
|
||||
let blocked = send(
|
||||
&app,
|
||||
&cookie,
|
||||
"DELETE",
|
||||
&format!("/api/admin/vocabularies/{vid}"),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(blocked.status(), StatusCode::CONFLICT);
|
||||
|
||||
let body: serde_json::Value =
|
||||
serde_json::from_slice(&blocked.into_body().collect().await.unwrap().to_bytes()).unwrap();
|
||||
assert_eq!(body["count"], 1);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user