Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Match the public and private APIs for content reading #386

Merged
merged 8 commits into from
Dec 20, 2023
37 changes: 27 additions & 10 deletions wnfs-wasm/src/fs/private/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use crate::{
value,
};
use chrono::{DateTime, Utc};
use js_sys::{Date, Promise, Uint8Array};
use js_sys::{Date, Number, Promise, Uint8Array};
use std::rc::Rc;
use wasm_bindgen::{prelude::wasm_bindgen, JsValue};
use wasm_bindgen_futures::future_to_promise;
Expand Down Expand Up @@ -86,23 +86,40 @@ impl PrivateFile {
/// Gets the entire content of a file.
#[wasm_bindgen(js_name = "getContent")]
pub fn get_content(&self, forest: &PrivateForest, store: BlockStore) -> JsResult<Promise> {
self.read_at(value!(0).into(), None, forest, store)
}

/// Gets the metadata of this file.
pub fn metadata(&self) -> JsResult<JsValue> {
JsMetadata(self.0.get_metadata()).try_into()
}

/// Gets the content of the file at given offset & with an optional byte limit.
#[wasm_bindgen(js_name = "readAt")]
pub fn read_at(
&self,
byte_offset: Number,
limit: Option<Number>,
forest: &PrivateForest,
store: BlockStore,
) -> JsResult<Promise> {
let file = Rc::clone(&self.0);
let store = ForeignBlockStore(store);
let forest = Rc::clone(&forest.0);

let byte_offset = f64::from(byte_offset) as u64;
let limit = limit.map(|lim| f64::from(lim) as usize);

Ok(future_to_promise(async move {
let content = file
.get_content(&forest, &store)
let result = file
.read_at(byte_offset, limit, &forest, &store)
.await
.map_err(error("Cannot get content of file"))?;
.map_err(error("Cannot read file"))?;

Ok(value!(Uint8Array::from(content.as_slice())))
}))
}
let uint8array = Uint8Array::from(result.as_ref());

/// Gets the metadata of this file.
pub fn metadata(&self) -> JsResult<JsValue> {
JsMetadata(self.0.get_metadata()).try_into()
Ok(value!(uint8array))
}))
}

/// Gets a unique id for node.
Expand Down
6 changes: 6 additions & 0 deletions wnfs-wasm/src/fs/public/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,12 @@ impl PublicFile {
arr
}

/// Gets the entire content of a file.
#[wasm_bindgen(js_name = "getContent")]
pub fn get_content(&self, store: BlockStore) -> JsResult<Promise> {
self.read_at(value!(0).into(), None, store)
}

/// Gets the metadata of this file.
pub fn metadata(&self) -> JsResult<JsValue> {
JsMetadata(self.0.get_metadata()).try_into()
Expand Down
Loading
Loading