use serde::{Deserialize, Serialize};
pub const DEFAULT_SESSION_ID: &str = "__default__";
#[derive(Debug, Deserialize)]
pub struct RawRequest {
pub id: String,
pub command: String,
#[serde(default)]
pub lsp_hints: Option<serde_json::Value>,
#[serde(default)]
pub session_id: Option<String>,
#[serde(flatten)]
pub params: serde_json::Value,
}
impl RawRequest {
pub fn session(&self) -> &str {
self.session_id.as_deref().unwrap_or(DEFAULT_SESSION_ID)
}
}
#[derive(Debug, Serialize)]
pub struct Response {
pub id: String,
pub success: bool,
#[serde(flatten)]
pub data: serde_json::Value,
}
#[derive(Debug, Deserialize)]
pub struct EchoParams {
pub message: String,
}
impl Response {
pub fn success(id: impl Into<String>, data: serde_json::Value) -> Self {
Response {
id: id.into(),
success: true,
data,
}
}
pub fn error(id: impl Into<String>, code: &str, message: impl Into<String>) -> Self {
Response {
id: id.into(),
success: false,
data: serde_json::json!({
"code": code,
"message": message.into(),
}),
}
}
pub fn error_with_data(
id: impl Into<String>,
code: &str,
message: impl Into<String>,
extra: serde_json::Value,
) -> Self {
let mut data = serde_json::json!({
"code": code,
"message": message.into(),
});
if let (Some(base), Some(ext)) = (data.as_object_mut(), extra.as_object()) {
for (k, v) in ext {
base.insert(k.clone(), v.clone());
}
}
Response {
id: id.into(),
success: false,
data,
}
}
}