MCPcopy Index your code
hub / github.com/aiscriptdev/aiscript / response_to_object

Function response_to_object

aiscript-vm/src/stdlib/http.rs:51–111  ·  view source on GitHub ↗
(
    ctx: Context<'_>,
    response: reqwest::Response,
)

Source from the content-addressed store, hash-verified

49}
50
51async fn response_to_object(
52 ctx: Context<'_>,
53 response: reqwest::Response,
54) -> Result<Value<'_>, VmError> {
55 let mut resp_obj = Object::default();
56
57 let status = response.status();
58 resp_obj
59 .fields
60 .insert(ctx.intern(b"status"), Value::Number(status.as_u16() as f64));
61
62 resp_obj.fields.insert(
63 ctx.intern(b"statusText"),
64 Value::String(ctx.intern(status.canonical_reason().unwrap_or("").as_bytes())),
65 );
66
67 resp_obj
68 .fields
69 .insert(ctx.intern(b"ok"), Value::Boolean(status.is_success()));
70
71 let mut headers_obj = Object::default();
72 for (name, value) in response.headers() {
73 headers_obj.fields.insert(
74 ctx.intern(name.as_str().as_bytes()),
75 Value::String(ctx.intern(value.to_str().unwrap_or("").as_bytes())),
76 );
77 }
78 resp_obj.fields.insert(
79 ctx.intern(b"headers"),
80 Value::Object(Gc::new(&ctx, RefLock::new(headers_obj))),
81 );
82
83 let headers = response.headers().clone();
84 // Add response text
85 let text = response
86 .text()
87 .await
88 .map_err(|e| VmError::RuntimeError(format!("Failed to read response body: {}", e)))?;
89
90 resp_obj.fields.insert(
91 ctx.intern(b"text"),
92 Value::String(ctx.intern(text.as_bytes())),
93 );
94
95 // Try to parse JSON if content-type is application/json
96 if let Some(content_type) = headers.get("content-type") {
97 if content_type
98 .to_str()
99 .unwrap_or("")
100 .contains("application/json")
101 {
102 if let Ok(json) = serde_json::from_str(&text) {
103 resp_obj
104 .fields
105 .insert(ctx.intern(b"json"), Value::from_serde_value(ctx, &json));
106 }
107 }
108 }

Callers 6

http_getFunction · 0.85
http_postFunction · 0.85
http_putFunction · 0.85
http_deleteFunction · 0.85
http_patchFunction · 0.85
http_headFunction · 0.85

Calls 9

ObjectClass · 0.85
RuntimeErrorClass · 0.85
as_bytesMethod · 0.80
to_strMethod · 0.80
containsMethod · 0.80
internMethod · 0.45
as_strMethod · 0.45
cloneMethod · 0.45
getMethod · 0.45

Tested by

no test coverage detected