Files
rustycms/src/referrers.rs

124 lines
4.0 KiB
Rust

//! Reverse index: for each (collection, slug) store which entries reference it.
//! Updated on create/update/delete so we can answer "where is this entry referenced?".
//! Persisted as a single JSON file in the content directory (e.g. `content/_referrers.json`).
use std::collections::HashMap;
use std::path::Path;
use serde::{Deserialize, Serialize};
/// One referrer: an entry that points to another via a reference field.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct Referrer {
pub collection: String,
pub slug: String,
pub field: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub locale: Option<String>,
}
fn key(collection: &str, slug: &str) -> String {
format!("{}:{}", collection, slug)
}
/// In-memory index: (ref_collection, ref_slug) -> list of referrers.
/// Persisted as JSON file so it survives restarts.
#[derive(Debug, Default, Clone)]
pub struct ReferrerIndex {
/// "collection:slug" -> list of referrers
index: HashMap<String, Vec<Referrer>>,
}
impl ReferrerIndex {
pub fn new() -> Self {
Self::default()
}
/// Load index from JSON file. Missing or invalid file => empty index.
pub fn load(path: &Path) -> Self {
let data = match std::fs::read_to_string(path) {
Ok(s) => s,
_ => return Self::new(),
};
let index: HashMap<String, Vec<Referrer>> = match serde_json::from_str(&data) {
Ok(m) => m,
_ => return Self::new(),
};
Self { index }
}
/// Persist index to JSON file.
pub fn save(&self, path: &Path) -> std::io::Result<()> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let data = serde_json::to_string_pretty(&self.index)?;
std::fs::write(path, data)
}
/// Remove this (referrer_collection, referrer_slug) from the referrer list of (ref_collection, ref_slug).
pub fn remove_referrer(
&mut self,
ref_collection: &str,
ref_slug: &str,
referrer: &Referrer,
) {
let k = key(ref_collection, ref_slug);
if let Some(list) = self.index.get_mut(&k) {
list.retain(|r| {
r.collection != referrer.collection
|| r.slug != referrer.slug
|| r.field != referrer.field
|| r.locale != referrer.locale
});
if list.is_empty() {
self.index.remove(&k);
}
}
}
/// Add this referrer to the list for (ref_collection, ref_slug).
pub fn add_referrer(
&mut self,
ref_collection: &str,
ref_slug: &str,
referrer: Referrer,
) {
let k = key(ref_collection, ref_slug);
self.index
.entry(k)
.or_default()
.push(referrer);
}
/// Remove all referrers that are (referrer_collection, referrer_slug) from every key.
/// Used when an entry is updated: clear its old refs, then add new refs.
pub fn remove_all_referrers_from(&mut self, referrer_collection: &str, referrer_slug: &str) {
let keys_to_check: Vec<String> = self.index.keys().cloned().collect();
for k in keys_to_check {
let empty = if let Some(list) = self.index.get_mut(&k) {
list.retain(|r| r.collection != referrer_collection || r.slug != referrer_slug);
list.is_empty()
} else {
false
};
if empty {
self.index.remove(&k);
}
}
}
/// Get all referrers of (collection, slug).
pub fn get_referrers(&self, collection: &str, slug: &str) -> Vec<Referrer> {
self.index
.get(&key(collection, slug))
.cloned()
.unwrap_or_default()
}
/// Remove the list for (ref_collection, ref_slug). Used when that entry is deleted.
pub fn remove_referenced_entry(&mut self, ref_collection: &str, ref_slug: &str) {
self.index.remove(&key(ref_collection, ref_slug));
}
}