better-fetch 0.6.1

Typed HTTP client layer on top of reqwest — inspired by @better-fetch/fetch
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
//! JSON Schema (schemars) → OpenAPI `components` conversion.

use std::collections::HashSet;

use indexmap::IndexMap;
use schemars::schema::RootSchema;
use serde_json::Value;

use super::document::{OpenApiParameter, OpenApiSchemaRef};

/// Collected component schemas with stable `$ref` paths.
#[derive(Debug, Default)]
pub(crate) struct SchemaCatalog {
    pub schemas: IndexMap<String, Value>,
}

impl SchemaCatalog {
    /// Register a [`RootSchema`] and return a component `$ref`, or `None` for null/empty types.
    pub fn register(&mut self, preferred_name: &str, root: &RootSchema) -> Option<String> {
        if is_null_schema(root) {
            return None;
        }

        let mut value = serde_json::to_value(root).ok()?;
        if let Some(defs) = value
            .as_object_mut()
            .and_then(|obj| obj.remove("definitions"))
        {
            if let Some(def_map) = defs.as_object() {
                for (name, schema) in def_map {
                    self.insert_component(name, schema.clone());
                }
            }
        }

        if let Some(obj) = value.as_object_mut() {
            obj.remove("$schema");
        }

        let name = value
            .get("title")
            .and_then(|t| t.as_str())
            .filter(|title| *title != "Null")
            .map(sanitize_component_name)
            .unwrap_or_else(|| sanitize_component_name(preferred_name));

        self.insert_component(&name, value);
        Some(format!("#/components/schemas/{name}"))
    }

    fn insert_component(&mut self, name: &str, schema: Value) {
        let name = sanitize_component_name(name);
        if self.schemas.contains_key(&name) {
            return;
        }
        let cleaned = nullable_rewrite(rewrite_schema_refs(strip_meta(schema)));
        self.schemas.insert(name, cleaned);
    }
}

pub(crate) fn schema_ref(ref_path: String) -> OpenApiSchemaRef {
    OpenApiSchemaRef::Ref { ref_path }
}

pub(crate) fn is_null_schema(root: &RootSchema) -> bool {
    let Ok(value) = serde_json::to_value(root) else {
        return true;
    };
    value.get("type").and_then(|t| t.as_str()) == Some("null")
        || value.get("title").and_then(|t| t.as_str()) == Some("Null")
}

/// Convert better-fetch path templates (`/items/:id`) to OpenAPI (`/items/{id}`).
pub(crate) fn to_openapi_path(path: &str) -> String {
    let mut out = String::new();
    for segment in path.split('/') {
        if segment.is_empty() {
            continue;
        }
        out.push('/');
        if let Some(name) = segment.strip_prefix(':') {
            out.push('{');
            out.push_str(name);
            out.push('}');
        } else {
            out.push_str(segment);
        }
    }
    if out.is_empty() {
        "/".to_string()
    } else {
        out
    }
}

pub(crate) fn path_param_names(path: &str) -> HashSet<String> {
    crate::path_params::path_param_names(path)
        .into_iter()
        .collect()
}

pub(crate) fn operation_id(method: &http::Method, path: &str) -> String {
    let slug = path_slug(path);
    format!("{}{}", method.as_str().to_ascii_lowercase(), slug)
}

/// Build query/path parameters from a schemars object schema.
pub(crate) fn parameters_from_schema(
    root: &RootSchema,
    location: &str,
    path_names: &HashSet<String>,
    catalog: &mut SchemaCatalog,
    preferred_prefix: &str,
) -> Vec<OpenApiParameter> {
    if is_null_schema(root) {
        return Vec::new();
    }

    let Ok(mut value) = serde_json::to_value(root) else {
        return Vec::new();
    };
    let Some(properties) = value
        .as_object_mut()
        .and_then(|obj| obj.remove("properties"))
        .and_then(|p| p.as_object().cloned())
    else {
        return Vec::new();
    };

    let required: HashSet<String> = value
        .get("required")
        .and_then(|r| r.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(str::to_string))
                .collect()
        })
        .unwrap_or_default();

    let mut params = Vec::new();
    for (name, prop_schema) in properties {
        if location == "path" && !path_names.contains(&name) {
            continue;
        }
        if location == "query" && path_names.contains(&name) {
            continue;
        }

        let inline = nullable_rewrite(rewrite_schema_refs(prop_schema));
        let schema = if let Some(ref_path) = inline_ref_to_component(
            &inline,
            catalog,
            &format!("{preferred_prefix}{}", capitalize(&name)),
        ) {
            OpenApiSchemaRef::Ref { ref_path }
        } else {
            OpenApiSchemaRef::Inline(inline)
        };

        params.push(OpenApiParameter {
            name: name.clone(),
            location: location.to_string(),
            description: None,
            required: location == "path" || required.contains(&name),
            schema,
        });
    }

    params.sort_by(|a, b| a.name.cmp(&b.name));
    params
}

fn inline_ref_to_component(
    schema: &Value,
    catalog: &mut SchemaCatalog,
    preferred_name: &str,
) -> Option<String> {
    if let Some(obj) = schema.as_object() {
        if obj.len() == 1 {
            if let Some(r) = obj.get("$ref").and_then(|v| v.as_str()) {
                if let Some(name) = r.strip_prefix("#/definitions/") {
                    let full = format!("#/components/schemas/{}", sanitize_component_name(name));
                    if !catalog.schemas.contains_key(&sanitize_component_name(name)) {
                        return None;
                    }
                    return Some(full);
                }
            }
        }
    }
    if schema.is_object() && schema.as_object().is_some_and(|o| !o.is_empty()) {
        let name = sanitize_component_name(preferred_name);
        if !catalog.schemas.contains_key(&name) {
            catalog.schemas.insert(
                name.clone(),
                nullable_rewrite(rewrite_schema_refs(schema.clone())),
            );
        }
        return Some(format!("#/components/schemas/{name}"));
    }
    None
}

fn strip_meta(mut value: Value) -> Value {
    if let Some(obj) = value.as_object_mut() {
        obj.remove("$schema");
        obj.remove("definitions");
    }
    value
}

fn rewrite_schema_refs(value: Value) -> Value {
    match value {
        Value::Object(mut map) => {
            if let Some(Value::String(reference)) = map.get("$ref") {
                if let Some(rest) = reference.strip_prefix("#/definitions/") {
                    map.insert(
                        "$ref".into(),
                        Value::String(format!(
                            "#/components/schemas/{}",
                            sanitize_component_name(rest)
                        )),
                    );
                }
            }
            let keys: Vec<String> = map.keys().cloned().collect();
            for key in keys {
                if let Some(v) = map.remove(&key) {
                    map.insert(key, rewrite_schema_refs(v));
                }
            }
            Value::Object(map)
        }
        Value::Array(items) => Value::Array(items.into_iter().map(rewrite_schema_refs).collect()),
        other => other,
    }
}

fn is_null_variant(v: &Value) -> bool {
    v.as_object()
        .is_some_and(|o| o.len() == 1 && o.get("type").and_then(Value::as_str) == Some("null"))
}

/// Converts JSON Schema (draft-07) nullability into OpenAPI 3.0 `nullable: true`.
///
/// Handles both `"type": [..., "null"]` (option of primitive) and
/// `"anyOf"`/`"oneOf"` variants containing `{"type": "null"}` (option of `$ref`/struct).
fn nullable_rewrite(value: Value) -> Value {
    let Value::Object(mut map) = value else {
        return match value {
            Value::Array(items) => Value::Array(items.into_iter().map(nullable_rewrite).collect()),
            other => other,
        };
    };

    if let Some(Value::Array(types)) = map.get("type").cloned() {
        if types.iter().any(|t| t == "null") {
            let rest: Vec<Value> = types.into_iter().filter(|t| t != "null").collect();
            match rest.len() {
                0 => {
                    map.remove("type");
                }
                1 => {
                    map.insert("type".into(), rest.into_iter().next().unwrap());
                }
                _ => {
                    map.insert("type".into(), Value::Array(rest));
                }
            }
            map.insert("nullable".into(), Value::Bool(true));
        }
    }

    for key in ["anyOf", "oneOf"] {
        let Some(Value::Array(variants)) = map.get(key).cloned() else {
            continue;
        };
        if !variants.iter().any(is_null_variant) {
            continue;
        }
        let mut rest: Vec<Value> = variants
            .into_iter()
            .filter(|v| !is_null_variant(v))
            .collect();
        map.insert("nullable".into(), Value::Bool(true));
        if rest.len() == 1 {
            map.remove(key);
            let only = rest.pop().unwrap();
            if only.as_object().is_some_and(|o| o.contains_key("$ref")) {
                // A `$ref` ignores sibling keywords in OpenAPI 3.0; wrap so `nullable` applies.
                map.insert("allOf".into(), Value::Array(vec![only]));
            } else if let Value::Object(inner) = only {
                for (k, v) in inner {
                    map.entry(k).or_insert(v);
                }
            }
        } else {
            map.insert(key.into(), Value::Array(rest));
        }
    }

    let keys: Vec<String> = map.keys().cloned().collect();
    for key in keys {
        if let Some(v) = map.remove(&key) {
            map.insert(key, nullable_rewrite(v));
        }
    }
    Value::Object(map)
}

pub(crate) fn sanitize_component_name(name: &str) -> String {
    let mut out = String::new();
    let mut upper_next = true;
    for ch in name.chars() {
        if ch.is_ascii_alphanumeric() {
            if upper_next {
                out.extend(ch.to_uppercase());
                upper_next = false;
            } else {
                out.push(ch);
            }
        } else {
            upper_next = true;
        }
    }
    if out.is_empty() {
        "Schema".into()
    } else {
        out
    }
}

fn capitalize(s: &str) -> String {
    let mut chars = s.chars();
    match chars.next() {
        None => String::new(),
        Some(c) => c.to_uppercase().collect::<String>() + chars.as_str(),
    }
}

fn path_slug(path: &str) -> String {
    path.split('/')
        .filter(|s| !s.is_empty())
        .map(|segment| {
            if let Some(name) = segment.strip_prefix(':') {
                capitalize(name)
            } else {
                capitalize(segment)
            }
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use schemars::JsonSchema;

    #[test]
    fn converts_colon_path_params() {
        assert_eq!(to_openapi_path("/todos/:id"), "/todos/{id}");
        assert_eq!(path_param_names("/todos/:id"), HashSet::from(["id".into()]));
    }

    #[test]
    fn null_unit_schema_skipped() {
        assert!(is_null_schema(&schemars::schema_for!(())));
    }

    #[derive(JsonSchema)]
    #[expect(dead_code)]
    struct Sample {
        name: String,
    }

    #[test]
    fn registers_schema_with_title() {
        let mut catalog = SchemaCatalog::default();
        let ref_path = catalog
            .register("Fallback", &schemars::schema_for!(Sample))
            .unwrap();
        assert_eq!(ref_path, "#/components/schemas/Sample");
        assert!(catalog.schemas.contains_key("Sample"));
    }

    #[derive(JsonSchema)]
    #[expect(dead_code)]
    struct Inner {
        a: u32,
    }

    #[derive(JsonSchema)]
    #[expect(dead_code)]
    struct Nullable {
        name: Option<String>,
        inner: Option<Inner>,
        plain: String,
    }

    #[test]
    fn option_fields_become_openapi_nullable() {
        let mut catalog = SchemaCatalog::default();
        catalog
            .register("Nullable", &schemars::schema_for!(Nullable))
            .unwrap();
        let schema = &catalog.schemas["Nullable"];
        let props = &schema["properties"];

        // Option<primitive>: single type + nullable, no "null" in a type array.
        assert_eq!(props["name"]["type"], serde_json::json!("string"));
        assert_eq!(props["name"]["nullable"], serde_json::json!(true));

        // Option<struct>: anyOf+null collapses to allOf+nullable (no null variant left).
        assert_eq!(props["inner"]["nullable"], serde_json::json!(true));
        assert!(props["inner"].get("anyOf").is_none());

        // Non-optional field is untouched.
        assert_eq!(props["plain"]["type"], serde_json::json!("string"));
        assert!(props["plain"].get("nullable").is_none());

        // No residual draft-07 null typing anywhere in the serialized component.
        let dumped = serde_json::to_string(schema).unwrap();
        assert!(!dumped.contains("\"null\""));
    }
}