pub use vta_sdk::did_templates::DidTemplateRecord;
use crate::error::AppError;
use crate::store::KeyspaceHandle;
const GLOBAL_PREFIX: &str = "tpl:global:";
const CONTEXT_PREFIX: &str = "tpl:ctx:";
fn global_key(name: &str) -> String {
format!("{GLOBAL_PREFIX}{name}")
}
fn context_prefix(context_id: &str) -> String {
format!("{CONTEXT_PREFIX}{context_id}:")
}
fn context_key(context_id: &str, name: &str) -> String {
format!("{CONTEXT_PREFIX}{context_id}:{name}")
}
pub async fn get_global_template(
ks: &KeyspaceHandle,
name: &str,
) -> Result<Option<DidTemplateRecord>, AppError> {
ks.get(global_key(name)).await
}
pub async fn store_global_template(
ks: &KeyspaceHandle,
record: &DidTemplateRecord,
) -> Result<(), AppError> {
ks.insert(global_key(&record.template.name), record).await
}
pub async fn delete_global_template(ks: &KeyspaceHandle, name: &str) -> Result<(), AppError> {
ks.remove(global_key(name)).await
}
pub async fn list_global_templates(
ks: &KeyspaceHandle,
) -> Result<Vec<DidTemplateRecord>, AppError> {
let raw = ks.prefix_iter_raw(GLOBAL_PREFIX).await?;
let mut records = Vec::with_capacity(raw.len());
for (_key, value) in raw {
let record: DidTemplateRecord = serde_json::from_slice(&value)?;
records.push(record);
}
records.sort_by(|a, b| a.template.name.cmp(&b.template.name));
Ok(records)
}
pub async fn get_context_template(
ks: &KeyspaceHandle,
context_id: &str,
name: &str,
) -> Result<Option<DidTemplateRecord>, AppError> {
ks.get(context_key(context_id, name)).await
}
pub async fn store_context_template(
ks: &KeyspaceHandle,
context_id: &str,
record: &DidTemplateRecord,
) -> Result<(), AppError> {
ks.insert(context_key(context_id, &record.template.name), record)
.await
}
pub async fn delete_context_template(
ks: &KeyspaceHandle,
context_id: &str,
name: &str,
) -> Result<(), AppError> {
ks.remove(context_key(context_id, name)).await
}
pub async fn list_context_templates(
ks: &KeyspaceHandle,
context_id: &str,
) -> Result<Vec<DidTemplateRecord>, AppError> {
let raw = ks.prefix_iter_raw(context_prefix(context_id)).await?;
let mut records = Vec::with_capacity(raw.len());
for (_key, value) in raw {
let record: DidTemplateRecord = serde_json::from_slice(&value)?;
records.push(record);
}
records.sort_by(|a, b| a.template.name.cmp(&b.template.name));
Ok(records)
}
pub async fn delete_all_context_templates(
ks: &KeyspaceHandle,
context_id: &str,
) -> Result<usize, AppError> {
let records = list_context_templates(ks, context_id).await?;
let count = records.len();
for r in records {
ks.remove(context_key(context_id, &r.template.name)).await?;
}
Ok(count)
}