Cotton code
46 lines · 2.3 KB · RustRaw
//! The record a held card stands for, as the held card's reads read it//! (`shell.opened`, `cards.pages`, `cards.when`): its table's definition and//! its columns.use crate::methods::MethodError;use crate::shell::client::ClientController;use cotton_core::definitions::TableDefinition;use serde_json::{json, Map, Value};/// One record a card stands for, as the fan calls read it: its table's/// definition and its columns, with the core's `deletable` beside them.pub(crate) struct HeldCard {    pub table: String,    pub id: String,    pub definition: TableDefinition,    pub data: Map<String, Value>,}pub(crate) fn read_card(client: &ClientController, request: &Value, method: &str) -> Result<HeldCard, MethodError> {    let bad = |why: String| MethodError::new("bad_request", why);    let table = request["table"].as_str().ok_or_else(|| bad(format!("{method} takes the record's table")))?;    let id = request["id"].as_str().ok_or_else(|| bad(format!("{method} takes the record's id")))?;    let definition = read_definition(client, table, method)?;    // The record as `records.get` answers it, with what only this device    // says about it (This device's own row: its words and its acts), never a    // second reader beside that one.    let record = super::records::call(client, "records.get", &json!({ "table": table, "id": id }))?;    let mut data = record.get("data").unwrap_or(&record).as_object().cloned().unwrap_or_default();    // The core's word that the record cannot go alone rides beside its columns.    if let Some(deletable) = record.get("deletable") {        data.insert("deletable".to_string(), deletable.clone());    }    Ok(HeldCard { table: table.to_string(), id: id.to_string(), definition, data })}/// The definition of `table` in this database.pub(crate) fn read_definition(client: &ClientController, table: &str, method: &str) -> Result<TableDefinition, MethodError> {    let mut definition = None;    client        .read_rows(method, &mut |ctx| {            definition = Some(cotton_tools::mcp::handlers::tables::definition(ctx, table).map_err(|failure| failure.to_string())?);            Ok(Value::Null)        })        .map_err(|why| MethodError::new("unreadable", why))?;    definition.ok_or_else(|| MethodError::new("bad_request", format!("{method} names a table of this database")))}