1pub const DEFAULT_BODY_LIMIT: usize = 2 * 1024 * 1024;
12
13pub fn coerce_value(raw: &str) -> serde_json::Value {
22 if raw.is_empty() {
23 return serde_json::Value::Null;
24 }
25
26 if raw.eq_ignore_ascii_case("true") {
27 return serde_json::Value::Bool(true);
28 }
29 if raw.eq_ignore_ascii_case("false") {
30 return serde_json::Value::Bool(false);
31 }
32 if raw.eq_ignore_ascii_case("null") {
33 return serde_json::Value::Null;
34 }
35
36 if let Ok(n) = raw.parse::<i64>() {
37 return serde_json::Value::Number(n.into());
38 }
39
40 if let Ok(f) = raw.parse::<f64>() {
41 if f.is_finite() {
42 if let Some(n) = serde_json::Number::from_f64(f) {
43 return serde_json::Value::Number(n);
44 }
45 }
46 }
47
48 serde_json::Value::String(raw.to_string())
49}
50
51pub fn parse_query_string(query: &str) -> serde_json::Map<String, serde_json::Value> {
56 let mut map = serde_json::Map::new();
57
58 if query.is_empty() {
59 return map;
60 }
61
62 for pair in query.split('&') {
63 if pair.is_empty() {
64 continue;
65 }
66 let (key, raw_value) = match pair.split_once('=') {
67 Some((k, v)) => (k, v),
68 None => (pair, ""),
69 };
70
71 let key = url_decode(key);
72 let raw_value = url_decode(raw_value);
73
74 map.insert(key, coerce_value(&raw_value));
75 }
76
77 map
78}
79
80pub fn query_string_to_json(query: &str) -> serde_json::Value {
84 serde_json::Value::Object(parse_query_string(query))
85}
86
87pub fn cookies_to_json(cookie_header: &str) -> serde_json::Value {
91 let mut map = serde_json::Map::new();
92
93 if cookie_header.is_empty() {
94 return serde_json::Value::Object(map);
95 }
96
97 for cookie in cookie_header.split(';') {
98 let cookie = cookie.trim();
99 if cookie.is_empty() {
100 continue;
101 }
102 let (name, value) = match cookie.split_once('=') {
103 Some((n, v)) => (n.trim(), v.trim()),
104 None => (cookie.trim(), ""),
105 };
106 map.insert(name.to_string(), coerce_value(value));
107 }
108
109 serde_json::Value::Object(map)
110}
111
112use serde::Serialize;
117
118vld::schema! {
119 #[derive(Debug, Clone, Serialize)]
124 pub struct ErrorBody {
125 pub error: String => vld::string(),
126 }
127}
128
129vld::schema! {
130 #[derive(Debug, Clone, Serialize)]
134 pub struct ErrorWithMessage {
135 pub error: String => vld::string(),
136 pub message: String => vld::string(),
137 }
138}
139
140vld::schema! {
141 #[derive(Debug, Clone, Serialize)]
143 pub struct ValidationIssue {
144 pub path: String => vld::string(),
145 pub message: String => vld::string(),
146 }
147}
148
149vld::schema! {
150 #[derive(Debug, Clone, Serialize)]
153 pub struct ValidationIssueWithCode {
154 pub path: String => vld::string(),
155 pub message: String => vld::string(),
156 pub code: String => vld::string(),
157 }
158}
159
160vld::schema! {
161 #[derive(Debug, Clone, Serialize)]
164 pub struct ValidationErrorBody {
165 pub error: String => vld::string(),
166 pub issues: Vec<ValidationIssue> => vld::array(vld::nested(ValidationIssue::parse_value)),
167 }
168}
169
170fn format_path(path: &[vld::error::PathSegment]) -> String {
175 use vld::error::PathSegment;
176 let mut out = String::new();
177 for seg in path {
178 match seg {
179 PathSegment::Field(name) => {
180 out.push('.');
181 out.push_str(name);
182 }
183 PathSegment::Index(idx) => {
184 out.push('[');
185 out.push_str(&idx.to_string());
186 out.push(']');
187 }
188 }
189 }
190 out
191}
192
193pub fn format_issues(err: &vld::error::VldError) -> Vec<ValidationIssue> {
196 err.issues
197 .iter()
198 .map(|i| ValidationIssue {
199 path: format_path(&i.path),
200 message: i.message.clone(),
201 })
202 .collect()
203}
204
205pub fn format_vld_error(err: &vld::error::VldError) -> serde_json::Value {
210 let body = ValidationErrorBody {
211 error: "Validation failed".into(),
212 issues: format_issues(err),
213 };
214 serde_json::to_value(body).expect("ValidationErrorBody serialization cannot fail")
215}
216
217pub fn format_issues_with_code(err: &vld::error::VldError) -> Vec<ValidationIssueWithCode> {
222 err.issues
223 .iter()
224 .map(|issue| ValidationIssueWithCode {
225 path: format_path(&issue.path),
226 message: issue.message.clone(),
227 code: issue.code.key().to_string(),
228 })
229 .collect()
230}
231
232pub fn url_decode(input: &str) -> String {
236 let s = input.replace('+', " ");
237 let mut result = String::with_capacity(s.len());
238 let mut chars = s.chars();
239 while let Some(c) = chars.next() {
240 if c == '%' {
241 let hex: String = chars.by_ref().take(2).collect();
242 if let Ok(byte) = u8::from_str_radix(&hex, 16) {
243 result.push(byte as char);
244 } else {
245 result.push('%');
246 result.push_str(&hex);
247 }
248 } else {
249 result.push(c);
250 }
251 }
252 result
253}
254
255pub fn format_json_parse_error(message: &str) -> serde_json::Value {
265 serde_json::to_value(ErrorWithMessage {
266 error: "Invalid JSON".into(),
267 message: message.into(),
268 })
269 .expect("ErrorWithMessage serialization cannot fail")
270}
271
272pub fn format_utf8_error() -> serde_json::Value {
278 serde_json::to_value(ErrorBody {
279 error: "Invalid UTF-8".into(),
280 })
281 .expect("ErrorBody serialization cannot fail")
282}
283
284pub fn format_payload_too_large() -> serde_json::Value {
290 serde_json::to_value(ErrorBody {
291 error: "Payload too large".into(),
292 })
293 .expect("ErrorBody serialization cannot fail")
294}
295
296pub fn format_generic_error(error: &str) -> serde_json::Value {
302 serde_json::to_value(ErrorBody {
303 error: error.into(),
304 })
305 .expect("ErrorBody serialization cannot fail")
306}
307
308pub fn extract_path_param_names(pattern: &str) -> Vec<String> {
310 let mut names = Vec::new();
311 let mut chars = pattern.chars().peekable();
312 while let Some(c) = chars.next() {
313 if c == '{' {
314 let name: String = chars.by_ref().take_while(|&c| c != '}').collect();
315 if !name.is_empty() {
316 names.push(name);
317 }
318 }
319 }
320 names
321}