properly host client lib for deno importing (types working)

This commit is contained in:
mbecker20
2024-10-20 03:17:58 -04:00
parent 82324b00ee
commit 6fe5bc7420
2 changed files with 66 additions and 0 deletions

View File

@@ -26,6 +26,7 @@ mod resource;
mod stack;
mod state;
mod sync;
mod ts_client;
mod ws;
async fn app() -> anyhow::Result<()> {
@@ -76,6 +77,7 @@ async fn app() -> anyhow::Result<()> {
.nest("/execute", api::execute::router())
.nest("/listener", listener::router())
.nest("/ws", ws::router())
.nest("/client", ts_client::router())
.nest_service("/", serve_dir)
.fallback_service(frontend_index)
.layer(cors()?)

64
bin/core/src/ts_client.rs Normal file
View File

@@ -0,0 +1,64 @@
use anyhow::{anyhow, Context};
use axum::{
extract::Path,
http::{HeaderMap, HeaderValue},
routing::get,
Router,
};
use reqwest::StatusCode;
use serde::Deserialize;
use serror::AddStatusCodeError;
use tokio::fs;
use crate::config::core_config;
pub fn router() -> Router {
Router::new().route("/:path", get(serve_client_file))
}
const ALLOWED_FILES: &[&str] = &[
"lib.js",
"lib.d.ts",
"types.js",
"types.d.ts",
"responses.js",
"responses.d.ts",
];
#[derive(Deserialize)]
struct FilePath {
path: String,
}
async fn serve_client_file(
Path(FilePath { path }): Path<FilePath>,
) -> serror::Result<(HeaderMap, String)> {
if !ALLOWED_FILES.contains(&path.as_str()) {
return Err(
anyhow!("File {path} not found.")
.status_code(StatusCode::NOT_FOUND),
);
}
let contents = fs::read_to_string(format!(
"{}/client/{path}",
core_config().frontend_path
))
.await
.with_context(|| format!("Failed to read file: {path}"))?;
let mut headers = HeaderMap::new();
if path.ends_with(".js") {
headers.insert(
"X-TypeScript-Types",
HeaderValue::from_str(&format!(
"/client/{}",
path.replace(".js", ".d.ts")
))
.context("?? Invalid Header Value")?,
);
}
Ok((headers, contents))
}