Skip to main content

openapi_nexus/generators/rust/reqwest/
runtime.rs

1//! Hardcoded Rust runtime source files.
2//!
3//! The runtime provides a reqwest-based `Client`, `Error` enum, and `Auth`
4//! trait. These ship as-is in every generated SDK.
5
6use crate::codegen::traits::file_writer::FileInfo;
7use crate::generators::rust::common::runtime::render_api_call_error;
8use sigil_stitch::type_name::TypeName;
9
10const CLIENT_RS: &str = include_str!("runtime/client.rs.txt");
11const ERROR_RS: &str = include_str!("runtime/error.rs.txt");
12const AUTH_RS: &str = include_str!("runtime/auth.rs.txt");
13const MOD_RS: &str = include_str!("runtime/mod.rs.txt");
14const UPLOAD_FILE_RS: &str = include_str!("runtime/upload_file.rs.txt");
15
16/// Returns runtime files ready to write.
17pub fn runtime_files(
18    header: &str,
19    include_api_call_error: bool,
20    include_upload_file: bool,
21) -> Vec<FileInfo> {
22    let mut mod_rs = MOD_RS.to_string();
23    let mut error_rs = ERROR_RS.to_string();
24    if include_api_call_error {
25        error_rs.push('\n');
26        error_rs.push_str(
27            &render_api_call_error(TypeName::qualified("reqwest::header", "HeaderMap"))
28                .expect("reqwest ApiCallError runtime renders"),
29        );
30    }
31    let mut files = vec![
32        FileInfo::runtime("client.rs".to_string(), with_header(header, CLIENT_RS)),
33        FileInfo::runtime("error.rs".to_string(), with_header(header, &error_rs)),
34        FileInfo::runtime("auth.rs".to_string(), with_header(header, AUTH_RS)),
35    ];
36    if include_upload_file {
37        mod_rs.push_str(
38            "mod upload_file;\npub use upload_file::{multipart_header_value, UploadFile};\n",
39        );
40        files.push(FileInfo::runtime(
41            "upload_file.rs".to_string(),
42            with_header(header, UPLOAD_FILE_RS),
43        ));
44    }
45    files.push(FileInfo::runtime(
46        "mod.rs".to_string(),
47        with_header(header, &mod_rs),
48    ));
49    files
50}
51
52fn with_header(header: &str, body: &str) -> String {
53    let mut out = String::with_capacity(header.len() + body.len());
54    out.push_str(header);
55    out.push_str(body);
56    out
57}