feat(api): field-level set_fields 422 body (#28); enum-type SearchHitView.visibility (#38)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-06-05 15:32:48 +02:00
parent cd3606c0e9
commit d6dc1c9b57
6 changed files with 111 additions and 22 deletions
+50 -18
View File
@@ -510,6 +510,15 @@ pub(crate) async fn create_field_definition(
} }
} }
/// Field-level rejection detail for `set_fields`, so the UI can highlight the field.
#[derive(Serialize, ToSchema)]
pub(crate) struct FieldErrorView {
/// The flexible-field key that was rejected.
pub field: String,
/// Machine code: "unknown" | "type_mismatch" | "unresolved".
pub code: String,
}
/// Replace an object's flexible-field values (validated against the registry). /// Replace an object's flexible-field values (validated against the registry).
/// ///
/// **Replace semantics:** the body is the *complete* desired field set. Omitting a key /// **Replace semantics:** the body is the *complete* desired field set. Omitting a key
@@ -525,7 +534,7 @@ pub(crate) async fn create_field_definition(
(status = 401), (status = 401),
(status = 403), (status = 403),
(status = 404, description = "Object not found"), (status = 404, description = "Object not found"),
(status = 422, description = "Unknown field, type mismatch, or unresolved reference") (status = 422, body = FieldErrorView, description = "A field was rejected")
) )
)] )]
pub(crate) async fn set_fields( pub(crate) async fn set_fields(
@@ -533,34 +542,57 @@ pub(crate) async fn set_fields(
State(state): State<AppState>, State(state): State<AppState>,
Path(id): Path<String>, Path(id): Path<String>,
Json(values): Json<serde_json::Map<String, serde_json::Value>>, Json(values): Json<serde_json::Map<String, serde_json::Value>>,
) -> Result<StatusCode, StatusCode> { ) -> axum::response::Response {
let object_id = id.parse::<ObjectId>().map_err(|_| StatusCode::NOT_FOUND)?; use axum::response::IntoResponse;
let mut tx = state let Ok(object_id) = id.parse::<ObjectId>() else {
.db return StatusCode::NOT_FOUND.into_response();
.pool() };
.begin()
.await let mut tx = match state.db.pool().begin().await {
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; Ok(tx) => tx,
Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),
};
let result = let result =
db::catalog::set_object_fields(&mut tx, actor(&auth.user), object_id, &values).await; db::catalog::set_object_fields(&mut tx, actor(&auth.user), object_id, &values).await;
match result { match result {
Ok(()) => { Ok(()) => {
tx.commit() if tx.commit().await.is_err() {
.await return StatusCode::INTERNAL_SERVER_ERROR.into_response();
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; }
reindex(&state, object_id).await; reindex(&state, object_id).await;
Ok(StatusCode::NO_CONTENT) StatusCode::NO_CONTENT.into_response()
} }
Err(db::catalog::FieldError::ObjectNotFound) => Err(StatusCode::NOT_FOUND), Err(db::catalog::FieldError::ObjectNotFound) => StatusCode::NOT_FOUND.into_response(),
Err(db::catalog::FieldError::Db(_)) => Err(StatusCode::INTERNAL_SERVER_ERROR), Err(db::catalog::FieldError::Db(_)) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
Err(db::catalog::FieldError::UnknownField(_)) => Err(StatusCode::UNPROCESSABLE_ENTITY), Err(db::catalog::FieldError::UnknownField(field)) => (
Err(db::catalog::FieldError::TypeMismatch { .. }) => Err(StatusCode::UNPROCESSABLE_ENTITY), StatusCode::UNPROCESSABLE_ENTITY,
Err(db::catalog::FieldError::Unresolved { .. }) => Err(StatusCode::UNPROCESSABLE_ENTITY), Json(FieldErrorView {
field,
code: "unknown".to_owned(),
}),
)
.into_response(),
Err(db::catalog::FieldError::TypeMismatch { field, .. }) => (
StatusCode::UNPROCESSABLE_ENTITY,
Json(FieldErrorView {
field,
code: "type_mismatch".to_owned(),
}),
)
.into_response(),
Err(db::catalog::FieldError::Unresolved { field, .. }) => (
StatusCode::UNPROCESSABLE_ENTITY,
Json(FieldErrorView {
field,
code: "unresolved".to_owned(),
}),
)
.into_response(),
} }
} }
+1
View File
@@ -28,6 +28,7 @@ pub(crate) struct SearchHitView {
pub object_number: String, pub object_number: String,
pub object_name: String, pub object_name: String,
pub brief_description: Option<String>, pub brief_description: Option<String>,
#[schema(value_type = domain::Visibility)]
pub visibility: String, pub visibility: String,
pub snippet: Option<String>, pub snippet: Option<String>,
} }
+1
View File
@@ -53,6 +53,7 @@ use crate::{
admin_objects::FieldDefinitionView, admin_objects::FieldDefinitionView,
admin_objects::NewFieldDefinitionRequest, admin_objects::NewFieldDefinitionRequest,
admin_objects::CreatedField, admin_objects::CreatedField,
admin_objects::FieldErrorView,
admin_vocab::VocabularyView, admin_vocab::VocabularyView,
admin_vocab::NewVocabularyRequest, admin_vocab::NewVocabularyRequest,
admin_vocab::NewTermRequest, admin_vocab::NewTermRequest,
+46
View File
@@ -434,6 +434,52 @@ async fn set_fields_and_list_field_definitions(pool: PgPool) {
assert_eq!(bad.status(), StatusCode::UNPROCESSABLE_ENTITY); assert_eq!(bad.status(), StatusCode::UNPROCESSABLE_ENTITY);
} }
#[sqlx::test(migrations = "../db/migrations")]
async fn set_fields_unknown_field_returns_field_detail(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 db = db::Db::from_pool(pool.clone());
let mut tx = db.pool().begin().await.unwrap();
let id = catalog::create_object(
&mut tx,
AuditActor::System,
&obj("A-1", "amphora", Visibility::Draft),
)
.await
.unwrap();
tx.commit().await.unwrap();
let app = build_app(state(pool));
let cookie = login(&app, "ed@example.com", "pw-editor-123").await;
let resp = app
.oneshot(
Request::builder()
.method("PUT")
.uri(format!("/api/admin/objects/{id}/fields"))
.header(header::COOKIE, &cookie)
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(r#"{"definitely_not_a_field":"x"}"#))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
let body: serde_json::Value =
serde_json::from_slice(&resp.into_body().collect().await.unwrap().to_bytes()).unwrap();
assert_eq!(body["field"], "definitely_not_a_field");
assert_eq!(body["code"], "unknown");
}
#[sqlx::test(migrations = "../db/migrations")] #[sqlx::test(migrations = "../db/migrations")]
async fn create_requires_auth(pool: PgPool) { async fn create_requires_auth(pool: PgPool) {
migrate_sessions(&db::Db::from_pool(pool.clone())) migrate_sessions(&db::Db::from_pool(pool.clone()))
+12 -3
View File
@@ -408,6 +408,13 @@ export interface components {
required: boolean; required: boolean;
vocabulary_id?: string | null; vocabulary_id?: string | null;
}; };
/** @description Field-level rejection detail for `set_fields`, so the UI can highlight the field. */
FieldErrorView: {
/** @description Machine code: "unknown" | "type_mismatch" | "unresolved". */
code: string;
/** @description The flexible-field key that was rejected. */
field: string;
};
LabelInput: { LabelInput: {
label: string; label: string;
lang: string; lang: string;
@@ -513,7 +520,7 @@ export interface components {
object_name: string; object_name: string;
object_number: string; object_number: string;
snippet?: string | null; snippet?: string | null;
visibility: string; visibility: components["schemas"]["Visibility"];
}; };
SearchResultsView: { SearchResultsView: {
/** @description Meilisearch's estimate of the total number of matches. */ /** @description Meilisearch's estimate of the total number of matches. */
@@ -1038,12 +1045,14 @@ export interface operations {
}; };
content?: never; content?: never;
}; };
/** @description Unknown field, type mismatch, or unresolved reference */ /** @description A field was rejected */
422: { 422: {
headers: { headers: {
[name: string]: unknown; [name: string]: unknown;
}; };
content?: never; content: {
"application/json": components["schemas"]["FieldErrorView"];
};
}; };
}; };
}; };
+1 -1
View File
@@ -79,7 +79,7 @@ export const searchHits: SearchHitView[] = [
object_number: `N-${i + 2}`, object_number: `N-${i + 2}`,
object_name: `Object ${i + 2}`, object_name: `Object ${i + 2}`,
brief_description: null, brief_description: null,
visibility: "internal", visibility: "internal" as const,
snippet: null, snippet: null,
})), })),
]; ];