Skip to content

Commit

Permalink
improvement: git rid of cloning in the build_static_asset method.
Browse files Browse the repository at this point in the history
  • Loading branch information
sentinel1909 committed Feb 19, 2025
1 parent c35fcab commit effa974
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 10 deletions.
16 changes: 9 additions & 7 deletions app/src/asset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,35 +4,37 @@
use mime_guess::from_path;
use pavex::request::path::PathParams;
use rust_embed_for_web::{EmbedableFile, RustEmbed};
use std::borrow::Cow;

// struct type to represent a static asset from the file system
#[derive(RustEmbed)]
#[folder = "../static"]
struct Asset;

#[PathParams]
pub struct GetFilenameParams {
filename: String,
pub struct GetFilenameParams<'a> {
filename: Cow<'a, str>,
}

// struct type to represent a static asset, CSS, JS, an image, or anything else
#[derive(Debug, Clone)]
pub struct StaticAsset {
pub name: String,
pub name: Cow<'static, str>,
pub data: Vec<u8>,
pub mime_type: &'static str,
pub mime_type: Cow<'static, str>,
}

// methods for the StaticAsset type
impl StaticAsset {
pub fn build_static_asset(params: PathParams<GetFilenameParams>) -> Self {
let file = params.0.filename;
Self {

Check warning on line 31 in app/src/asset.rs

View workflow job for this annotation

GitHub Actions / Format

Diff in /home/runner/work/pavex-html/pavex-html/app/src/asset.rs
name: file.clone(),
name: Cow::Owned(file.to_string()),
data: Asset::get(&file).unwrap().data(),
mime_type: from_path(&file)
mime_type: from_path(file.as_ref())
.first_raw()
.unwrap_or("application/octet-stream"),
.map(|s| Cow::Owned(s.to_string()))
.unwrap_or_else(|| Cow::Borrowed("application/octet-stream")),
}

Check warning on line 38 in app/src/asset.rs

View workflow job for this annotation

GitHub Actions / Format

Diff in /home/runner/work/pavex-html/pavex-html/app/src/asset.rs
}
}
2 changes: 1 addition & 1 deletion app/src/routes/static_assets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ impl TypedBody for StaticAsset {
type Body = Full<Bytes>;

Check warning on line 14 in app/src/routes/static_assets.rs

View workflow job for this annotation

GitHub Actions / Format

Diff in /home/runner/work/pavex-html/pavex-html/app/src/routes/static_assets.rs

fn content_type(&self) -> HeaderValue {
HeaderValue::from_static(self.mime_type)
HeaderValue::from_str(&self.mime_type).unwrap()
}

fn body(self) -> Self::Body {
Expand Down
9 changes: 7 additions & 2 deletions static/script.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
'use strict';
"use strict";

console.log("Hello, from JavaScript");
console.log("Hello, from JavaScript");

let date = new Date();
let year = date.getFullYear();

console.log(`It is: ${year}`);

0 comments on commit effa974

Please sign in to comment.