Skip to main content

rouchdb_views/
design_doc.rs

1use std::collections::HashMap;
2
3use serde::{Deserialize, Serialize};
4
5use rouchdb_core::error::{Result, RouchError};
6
7/// A CouchDB design document.
8///
9/// Design documents store view definitions, filter functions,
10/// validation functions, and other application logic.
11#[derive(Debug, Clone, Serialize, Deserialize)]
12pub struct DesignDocument {
13    #[serde(rename = "_id")]
14    pub id: String,
15    #[serde(rename = "_rev", skip_serializing_if = "Option::is_none")]
16    pub rev: Option<String>,
17    #[serde(default)]
18    pub views: HashMap<String, ViewDef>,
19    #[serde(default)]
20    pub filters: HashMap<String, String>,
21    #[serde(skip_serializing_if = "Option::is_none")]
22    pub validate_doc_update: Option<String>,
23    #[serde(default)]
24    pub shows: HashMap<String, String>,
25    #[serde(default)]
26    pub lists: HashMap<String, String>,
27    #[serde(default)]
28    pub updates: HashMap<String, String>,
29    #[serde(default, skip_serializing_if = "Option::is_none")]
30    pub language: Option<String>,
31}
32
33/// A view definition containing map and optional reduce functions.
34#[derive(Debug, Clone, Serialize, Deserialize)]
35pub struct ViewDef {
36    pub map: String,
37    #[serde(skip_serializing_if = "Option::is_none")]
38    pub reduce: Option<String>,
39}
40
41impl DesignDocument {
42    /// Parse a design document from a JSON value.
43    pub fn from_json(value: serde_json::Value) -> Result<Self> {
44        serde_json::from_value(value)
45            .map_err(|e| RouchError::BadRequest(format!("invalid design doc: {}", e)))
46    }
47
48    /// Convert to a JSON value.
49    pub fn to_json(&self) -> serde_json::Value {
50        serde_json::to_value(self).unwrap_or_default()
51    }
52
53    /// Get the design document name without the `_design/` prefix.
54    pub fn name(&self) -> &str {
55        self.id.strip_prefix("_design/").unwrap_or(&self.id)
56    }
57}