Skip to content

Commit 2f88fc8

Browse files
tabcatachingbrain
andauthored
docs: add custom hasher example to readme (#645)
Adds an example to the readme of how to use a custom hasher with the helia data importing utils. Closes: #640 --------- Co-authored-by: Alex Potsides <[email protected]>
1 parent c04dbf5 commit 2f88fc8

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

README.md

+37
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,43 @@ console.log(await d.get(retrievedObject.link))
108108
// { hello: 'world' }
109109
```
110110

111+
## 🔒 Custom Hasher
112+
113+
A [hasher](https://github.com/multiformats/js-multiformats?tab=readme-ov-file#multihash-hashers) is used to determine the immutable address of the content (aka the [**CID**](https://github.com/multiformats/cid?tab=readme-ov-file#what-is-it)) being imported into helia. The default hasher used by the methods above is [sha2-256 multihash](https://github.com/multiformats/js-multiformats?tab=readme-ov-file#multihash-hashers-1), but others can be provided with [AddOptions](https://helia.io/interfaces/_helia_dag_cbor.AddOptions.html). This is useful for applications that require hashers with specific properties; so in most cases keeping the default is recommended.
114+
115+
> **Changing the hasher will cause a different CID to be returned for the same content! In other words: the same content imported with different hashers is treated like unique content with a unique address.**
116+
117+
```js
118+
import { createHelia } from 'helia'
119+
import { dagCbor } from '@helia/dag-cbor'
120+
import { sha512 } from 'multiformats/hashes/sha2'
121+
122+
const helia = await createHelia()
123+
const d = dagCbor(helia)
124+
125+
const object1 = { hello: 'world' }
126+
127+
const cidWithSHA256 = await d.add(object1)
128+
const cidWithSHA512 = await d.add(object1, {
129+
hasher: sha512
130+
})
131+
132+
/** The same objects with different CIDs are treated as different objects */
133+
134+
console.log(cidWithSHA256)
135+
// CID(bafyreidykglsfhoixmivffc5uwhcgshx4j465xwqntbmu43nb2dzqwfvae)
136+
console.log(cidWithSHA512)
137+
// CID(bafyrgqhai26anf3i7pips7q22coa4sz2fr4gk4q4sqdtymvvjyginfzaqewveaeqdh524nsktaq43j65v22xxrybrtertmcfxufdam3da3hbk)
138+
139+
const retrievedObject1 = await d.get(cidWithSHA256)
140+
const retrievedObject2 = await d.get(cidWithSHA512)
141+
142+
console.log(retrievedObject1)
143+
// { hello: 'world' }
144+
console.log(retrievedObject2)
145+
// { hello: 'world' }
146+
```
147+
111148
# 🐾 Next steps
112149

113150
Check out the [helia-examples](https://github.com/ipfs-examples/helia-examples)

0 commit comments

Comments
 (0)