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.entry(name.to_string())
109 .or_insert_with(|| coerce_value(value));
110 }
111
112 serde_json::Value::Object(map)
113}
114
115use serde::Serialize;
120
121vld::schema! {
122 #[derive(Debug, Clone, Serialize)]
127 pub struct ErrorBody {
128 pub error: String => vld::string(),
129 }
130}
131
132vld::schema! {
133 #[derive(Debug, Clone, Serialize)]
137 pub struct ErrorWithMessage {
138 pub error: String => vld::string(),
139 pub message: String => vld::string(),
140 }
141}
142
143vld::schema! {
144 #[derive(Debug, Clone, Serialize)]
146 pub struct ValidationIssue {
147 pub path: String => vld::string(),
148 pub message: String => vld::string(),
149 }
150}
151
152vld::schema! {
153 #[derive(Debug, Clone, Serialize)]
156 pub struct ValidationIssueWithCode {
157 pub path: String => vld::string(),
158 pub message: String => vld::string(),
159 pub code: String => vld::string(),
160 }
161}
162
163vld::schema! {
164 #[derive(Debug, Clone, Serialize)]
167 pub struct ValidationErrorBody {
168 pub error: String => vld::string(),
169 pub issues: Vec<ValidationIssue> => vld::array(vld::nested(ValidationIssue::parse_value)),
170 }
171}
172
173fn format_path(path: &[vld::error::PathSegment]) -> String {
178 use vld::error::PathSegment;
179 let mut out = String::new();
180 for seg in path {
181 match seg {
182 PathSegment::Field(name) => {
183 out.push('.');
184 out.push_str(name);
185 }
186 PathSegment::Index(idx) => {
187 out.push('[');
188 out.push_str(&idx.to_string());
189 out.push(']');
190 }
191 }
192 }
193 out
194}
195
196pub fn format_issues(err: &vld::error::VldError) -> Vec<ValidationIssue> {
199 err.issues
200 .iter()
201 .map(|i| ValidationIssue {
202 path: format_path(&i.path),
203 message: i.message.clone(),
204 })
205 .collect()
206}
207
208pub fn format_vld_error(err: &vld::error::VldError) -> serde_json::Value {
213 let body = ValidationErrorBody {
214 error: "Validation failed".into(),
215 issues: format_issues(err),
216 };
217 serde_json::to_value(body).expect("ValidationErrorBody serialization cannot fail")
218}
219
220pub fn format_issues_with_code(err: &vld::error::VldError) -> Vec<ValidationIssueWithCode> {
225 err.issues
226 .iter()
227 .map(|issue| ValidationIssueWithCode {
228 path: format_path(&issue.path),
229 message: issue.message.clone(),
230 code: issue.code.key().to_string(),
231 })
232 .collect()
233}
234
235pub fn url_decode(input: &str) -> String {
239 let s = input.replace('+', " ");
240 let mut result = String::with_capacity(s.len());
241 let mut chars = s.chars();
242 while let Some(c) = chars.next() {
243 if c == '%' {
244 let hex: String = chars.by_ref().take(2).collect();
245 if let Ok(byte) = u8::from_str_radix(&hex, 16) {
246 result.push(byte as char);
247 } else {
248 result.push('%');
249 result.push_str(&hex);
250 }
251 } else {
252 result.push(c);
253 }
254 }
255 result
256}
257
258pub fn format_json_parse_error(message: &str) -> serde_json::Value {
268 serde_json::to_value(ErrorWithMessage {
269 error: "Invalid JSON".into(),
270 message: message.into(),
271 })
272 .expect("ErrorWithMessage serialization cannot fail")
273}
274
275pub fn format_utf8_error() -> serde_json::Value {
281 serde_json::to_value(ErrorBody {
282 error: "Invalid UTF-8".into(),
283 })
284 .expect("ErrorBody serialization cannot fail")
285}
286
287pub fn format_payload_too_large() -> serde_json::Value {
293 serde_json::to_value(ErrorBody {
294 error: "Payload too large".into(),
295 })
296 .expect("ErrorBody serialization cannot fail")
297}
298
299pub fn format_generic_error(error: &str) -> serde_json::Value {
305 serde_json::to_value(ErrorBody {
306 error: error.into(),
307 })
308 .expect("ErrorBody serialization cannot fail")
309}
310
311pub fn extract_path_param_names(pattern: &str) -> Vec<String> {
313 let mut names = Vec::new();
314 let mut chars = pattern.chars().peekable();
315 while let Some(c) = chars.next() {
316 if c == '{' {
317 let name: String = chars.by_ref().take_while(|&c| c != '}').collect();
318 if !name.is_empty() {
319 names.push(name);
320 }
321 }
322 }
323 names
324}