use rquickjs::Exception;
use rquickjs::Result;
use rquickjs::prelude::*;
#[derive(rquickjs::class::Trace, Default, Debug)]
#[rquickjs::class(rename_all = "camelCase")]
pub struct Response {
#[qjs(get)]
status: u16,
#[qjs(get)]
status_text: String,
#[qjs(get)]
ok: bool,
#[qjs(skip_trace)]
response: Option<reqwest::Response>,
}
impl Response {
pub fn new(response: reqwest::Response) -> Self {
Self {
status: response.status().as_u16(),
status_text: response
.status()
.canonical_reason()
.unwrap_or("")
.to_string(),
ok: response.status().is_success(),
response: Some(response),
}
}
}
#[rquickjs::methods(rename_all = "camelCase")]
impl Response {
#[qjs(get)]
pub fn body_used(&self) -> bool {
self.response.is_none()
}
#[qjs(rename = "text")]
pub async fn text(&mut self, ctx: Ctx<'_>) -> Result<String> {
let response = self
.response
.take()
.ok_or_else(|| Exception::throw_type(&ctx, "Body is unusable"))?;
response
.text()
.await
.map_err(|e| Exception::throw_message(&ctx, &e.to_string()))
}
#[qjs(rename = "json")]
pub async fn json<'js>(&mut self, ctx: Ctx<'js>) -> Result<rquickjs::Value<'js>> {
let text = self.text(ctx.clone()).await?;
ctx.json_parse(text)
}
}