summer_ipfs_client/
block.rs

1use crate::IpfsApi;
2
3use reqwest;
4use failure::Error;
5
6use std::io::Read;
7
8#[derive(Deserialize)]
9struct BlockPutResponse {
10    #[serde(rename = "Key")]
11    key: String,
12}
13
14impl IpfsApi {
15    pub fn block_put<S: 'static +  Read + Send>(&self, data: S) -> Result<String, Error> {
16        let mut url = self.get_url()?;
17        url.set_path("api/v0/block/put");
18
19        let mut res = {
20            let client = reqwest::Client::new();
21            client.post(url)
22            .multipart(reqwest::multipart::Form::new()
23                .part("arg", reqwest::multipart::Part::reader(data))
24                ).send()?
25        };
26
27        let json: BlockPutResponse = res.json()?;
28        Ok(json.key)
29    }
30
31    pub fn block_get(&self, hash: &str) -> Result<impl Iterator<Item=u8>, Error> {
32        let mut url = self.get_url()?;
33        url.set_path("api/v0/block/get");
34        url.query_pairs_mut()
35            .append_pair("arg", hash);
36
37        let resp = reqwest::get(url)?;
38        Ok(resp.bytes().filter(|x|x.is_ok()).map(|x|x.unwrap()))
39    }
40}
41
42#[cfg(test)]
43mod tests {
44    use crate::IpfsApi;
45
46    #[test]
47    fn test_block_put() {
48        let api = IpfsApi::new("127.0.0.1", 5001);
49
50        let hash = api.block_put("Hello world".as_bytes()).unwrap();
51
52        assert_eq!(hash, "QmV8cfu6n4NT5xRr2AHdKxFMTZEJrA44qgrBCr739BN9Wb");
53    }
54
55    #[test]
56    fn test_block_get() {
57        let api = IpfsApi::new("127.0.0.1", 5001);
58
59        let content = "Hello world".as_bytes();
60
61        let hash = api.block_put(content).unwrap();
62        let block: Vec<u8> = api.block_get(&hash).unwrap().collect();
63
64        assert_eq!(block, content);
65    }
66}