Skip to content

Commit

Permalink
remove TauriResponse class
Browse files Browse the repository at this point in the history
  • Loading branch information
lucasfernog committed Aug 7, 2023
1 parent 566d52e commit b80c169
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 96 deletions.
60 changes: 7 additions & 53 deletions plugins/http/guest-js/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,56 +30,6 @@ declare global {
}
}

async function readBody<T>(rid: number, kind: "blob" | "text"): Promise<T> {
return await window.__TAURI_INVOKE__("plugin:http|fetch_read_body", {
rid,
kind,
});
}

class TauriResponse extends Response {
_rid: number = 0;

blob(): Promise<Blob> {
return readBody<Uint8Array>(this._rid, "blob").then(
(bytes) =>
new Blob([bytes], {
type: this.headers.get("content-type") || "application/octet-stream",
}),
);
}

json(): Promise<unknown> {
return readBody<string>(this._rid, "text").then((data) => {
try {
return JSON.parse(data);
} catch (e) {
if (this.ok && data === "") {
return {};
} else if (this.ok) {
throw Error(`Failed to parse response \`${data}\` as JSON: ${e}`);
}
}
});
}

formData(): Promise<FormData> {
return this.json().then((json) => {
const form = new FormData();
for (const [key, value] of Object.entries(
json as Record<string, string | Blob>,
)) {
form.append(key, value);
}
return form;
});
}

text(): Promise<string> {
return readBody(this._rid, "text");
}
}

/**
* Options to configure the Rust client used to make fetch requests
*
Expand Down Expand Up @@ -112,7 +62,7 @@ export interface ClientOptions {
export async function fetch(
input: URL | Request | string,
init?: RequestInit & ClientOptions,
): Promise<TauriResponse> {
): Promise<Response> {
const maxRedirections = init?.maxRedirections;
const connectTimeout = init?.maxRedirections;

Expand Down Expand Up @@ -154,12 +104,16 @@ export async function fetch(
rid,
});

const res = new TauriResponse(null, {
const body = await window.__TAURI_INVOKE__<number[]>("plugin:http|fetch_read_body", {
rid,
});

const res = new Response(Uint8Array.from(body), {
headers,
status,
statusText,
});
res._rid = rid;

// url is read only but seems like we can do this
Object.defineProperty(res, "url", { value: url });

Expand Down
2 changes: 1 addition & 1 deletion plugins/http/src/api-iife.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

46 changes: 4 additions & 42 deletions plugins/http/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

use std::{collections::HashMap, str::FromStr, time::Duration};
use std::{collections::HashMap, time::Duration};

use http::{header, HeaderName, HeaderValue, Method, StatusCode};
use reqwest::redirect::Policy;
use serde::{de::Deserializer, Deserialize, Serialize};
use serde::Serialize;
use tauri::{command, AppHandle, Runtime};

use crate::{Error, FetchRequest, HttpExt, RequestId};
Expand All @@ -20,40 +20,6 @@ pub struct FetchResponse {
url: String,
}

#[derive(Serialize)]
#[serde(untagged)]
pub enum ResponseBody {
Blob(Vec<u8>),
Text(String),
}

pub enum BodyKind {
Blob,
Text,
}

impl FromStr for BodyKind {
type Err = &'static str;

fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"blob" => Ok(Self::Blob),
"text" => Ok(Self::Text),
_ => Err("unknown body kind"),
}
}
}

impl<'de> Deserialize<'de> for BodyKind {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let kind = String::deserialize(deserializer)?;
kind.parse().map_err(serde::de::Error::custom)
}
}

#[command]
pub async fn fetch<R: Runtime>(
app: AppHandle<R>,
Expand Down Expand Up @@ -202,15 +168,11 @@ pub async fn fetch_send<R: Runtime>(
pub(crate) async fn fetch_read_body<R: Runtime>(
app: AppHandle<R>,
rid: RequestId,
kind: BodyKind,
) -> crate::Result<ResponseBody> {
) -> crate::Result<Vec<u8>> {
let mut response_table = app.http().responses.lock().await;
let res = response_table
.remove(&rid)
.ok_or(Error::InvalidRequestId(rid))?;

match kind {
BodyKind::Blob => Ok(ResponseBody::Blob(res.bytes().await?.to_vec())),
BodyKind::Text => Ok(ResponseBody::Text(res.text().await?)),
}
Ok(res.bytes().await?.to_vec())
}

0 comments on commit b80c169

Please sign in to comment.