(
ctx: Context<'_>,
response: reqwest::Response,
)
| 49 | } |
| 50 | |
| 51 | async 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 | } |
no test coverage detected