Skip to content

Commit

Permalink
using sse: schema to fetch in App
Browse files Browse the repository at this point in the history
  • Loading branch information
lloydzhou committed Sep 27, 2024
1 parent 23f2b62 commit d84d51b
Show file tree
Hide file tree
Showing 4 changed files with 149 additions and 40 deletions.
51 changes: 35 additions & 16 deletions app/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ import { useEffect, useState } from "react";
import { showToast } from "./components/ui-lib";
import Locale from "./locales";
import { RequestMessage } from "./client/api";
import { ServiceProvider, REQUEST_TIMEOUT_MS } from "./constant";
import { fetch as tauriFetch, ResponseType } from "@tauri-apps/api/http";
import { ServiceProvider } from "./constant";

export function trimTopic(topic: string) {
// Fix an issue where double quotes still show in the Indonesian language
Expand Down Expand Up @@ -292,30 +291,50 @@ export function fetch(
options?: Record<string, unknown>,
): Promise<any> {
if (window.__TAURI__) {
const payload = options?.body || options?.data;
return tauriFetch(url, {
...options,
body:
payload &&
({
type: "Text",
payload,
} as any),
timeout: ((options?.timeout as number) || REQUEST_TIMEOUT_MS) / 1000,
responseType:
options?.responseType == "text" ? ResponseType.Text : ResponseType.JSON,
} as any);
const tauriUri = window.__TAURI__.convertFileSrc(url, "sse");
return window.fetch(tauriUri, options).then((r) => {
// 1. create response,
// TODO using event to get status and statusText and headers
const { status, statusText } = r;
const { readable, writable } = new TransformStream();
const res = new Response(readable, { status, statusText });
// 2. call fetch_read_body multi times, and write to Response.body
const writer = writable.getWriter();
let unlisten;
window.__TAURI__.event
.listen("sse-response", (e) => {
const { id, payload } = e;
console.log("event", id, payload);
writer.ready.then(() => {
if (payload !== 0) {
writer.write(new Uint8Array(payload));
} else {
writer.releaseLock();
writable.close();
unlisten && unlisten();
}
});
})
.then((u) => (unlisten = u));
return res;
});
}
return window.fetch(url, options);
}

if (undefined !== window) {
window.tauriFetch = fetch;
}

export function adapter(config: Record<string, unknown>) {
const { baseURL, url, params, ...rest } = config;
const path = baseURL ? `${baseURL}${url}` : url;
const fetchUrl = params
? `${path}?${new URLSearchParams(params as any).toString()}`
: path;
return fetch(fetchUrl as string, { ...rest, responseType: "text" });
return fetch(fetchUrl as string, rest)
.then((res) => res.text())
.then((data) => ({ data }));
}

export function safeLocalStorage(): {
Expand Down
86 changes: 62 additions & 24 deletions src-tauri/Cargo.lock

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

4 changes: 4 additions & 0 deletions src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,12 @@ tauri = { version = "1.5.4", features = [ "http-all",
"window-start-dragging",
"window-unmaximize",
"window-unminimize",
"linux-protocol-headers",
] }
tauri-plugin-window-state = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v1" }
percent-encoding = "2.3.1"
reqwest = "0.11.18"
futures-util = "0.3.30"

[features]
# this feature is used for production builds or when `devPath` points to the filesystem and the built-in dev server is disabled.
Expand Down
48 changes: 48 additions & 0 deletions src-tauri/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,57 @@
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use futures_util::{StreamExt};
use reqwest::Client;
use tauri::{ Manager};
use tauri::http::{ResponseBuilder};

fn main() {
tauri::Builder::default()
.plugin(tauri_plugin_window_state::Builder::default().build())
.register_uri_scheme_protocol("sse", |app_handle, request| {
let path = request.uri().strip_prefix("sse://localhost/").unwrap();
let path = percent_encoding::percent_decode(path.as_bytes())
.decode_utf8_lossy()
.to_string();
// println!("path : {}", path);
let client = Client::new();
let window = app_handle.get_window("main").unwrap();
// send http request
let body = reqwest::Body::from(request.body().clone());
let response_future = client.request(request.method().clone(), path)
.headers(request.headers().clone())
.body(body).send();

// get response and emit to client
tauri::async_runtime::spawn(async move {
let res = response_future.await;

match res {
Ok(res) => {
let mut stream = res.bytes_stream();

while let Some(chunk) = stream.next().await {
match chunk {
Ok(bytes) => {
window.emit("sse-response", bytes).unwrap();
}
Err(err) => {
println!("Error: {:?}", err);
}
}
}
window.emit("sse-response", 0).unwrap();
}
Err(err) => {
println!("Error: {:?}", err);
}
}
});
ResponseBuilder::new()
.header("Access-Control-Allow-Origin", "*")
.status(200).body("OK".into())
})
.run(tauri::generate_context!())
.expect("error while running tauri application");
}

0 comments on commit d84d51b

Please sign in to comment.