Skip to content

Commit

Permalink
docs: add example for storing dag-json data using the storeCar me…
Browse files Browse the repository at this point in the history
…hod (#2402)
  • Loading branch information
Alan Shaw authored May 30, 2023
1 parent 14cf3f0 commit 9779e3d
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions examples/client/node.js/storeCar-dagJSON.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { NFTStorage } from 'nft.storage'
import { CarWriter } from '@ipld/car'
import * as dagJSON from '@ipld/dag-json'
import { sha256 } from 'multiformats/hashes/sha2'
import { encode } from 'multiformats/block'

const token = 'API_KEY' // your API key from https://nft.storage/manage

async function main() {
const storage = new NFTStorage({ token })

// Encode data to DAG
const objToStore = { hello: 'world' }
const block = await encode({ value: objToStore, codec: dagJSON, hasher: sha256 })

// Encode DAG to CAR
const { writer, out } = CarWriter.create([block.cid])
writer.put(block)
writer.close()

const chunks = []
for await (const chunk of out) {
chunks.push(chunk)
}
const car = new Blob(chunks)

// Store CAR with NFT.Storage
await storage.storeCar(car, { decoders: [dagJSON] })
console.log(block.cid.toString())
}
main()

0 comments on commit 9779e3d

Please sign in to comment.