Skip to content

Commit 014eec0

Browse files
committed
Initial implementation
1 parent 90f2cd6 commit 014eec0

File tree

3 files changed

+158
-0
lines changed

3 files changed

+158
-0
lines changed

index.js

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
const CID = require("cids")
2+
3+
function parseJSON(bytes, callback) {
4+
const string = bytes.toString("utf8")
5+
let res = null,
6+
error = null
7+
try {
8+
res = { document: JSON.parse(string) }
9+
} catch (e) {
10+
error = e
11+
} finally {
12+
callback(error, res)
13+
}
14+
}
15+
16+
const ipldLoaders = {
17+
"dag-pb"(value, callback) {
18+
parseJSON(value.data, callback)
19+
},
20+
"dag-cbor"(value, callback) {
21+
callback(null, { document: value })
22+
},
23+
}
24+
25+
const documentLoaders = {
26+
"dweb:/ipfs/"(ipfs, path, callback) {
27+
ipfs.files.cat(path, (err, bytes) => {
28+
if (err) callback(err)
29+
else parseJSON(bytes, callback)
30+
})
31+
},
32+
"dweb:/ipld/"(ipfs, path, callback) {
33+
let cid
34+
try {
35+
cid = new CID(path)
36+
} catch (e) {
37+
callback(e)
38+
}
39+
if (ipldLoaders.hasOwnProperty(cid.codec))
40+
ipfs.dag.get(path, (err, { value }) => {
41+
if (err) callback(err)
42+
else ipldLoaders[cid.codec](value, callback)
43+
})
44+
else callback(new Error("Unrecognized IPLD format"))
45+
},
46+
}
47+
48+
const keys = Object.keys(documentLoaders)
49+
const getDocumentLoader = ipfs => (url, callback) => {
50+
const key = keys.find(key => url.indexOf(key) === 0)
51+
if (key) documentLoaders[key](ipfs, url.slice(key.length), callback)
52+
else callback(new Error("Could not load document", url))
53+
}
54+
55+
module.exports = getDocumentLoader

package-lock.json

Lines changed: 75 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
{
2+
"name": "jsonld-dweb-loader",
3+
"version": "1.0.0",
4+
"description": "JSON-LD document loader for IPFS and IPLD URIs",
5+
"main": "index.js",
6+
"scripts": {
7+
"test": "echo \"Error: no test specified\" && exit 1"
8+
},
9+
"repository": {
10+
"type": "git",
11+
"url": "git+https://github.com/joeltg/jsonld-dweb-loader.git"
12+
},
13+
"keywords": [
14+
"ipfs",
15+
"ipld",
16+
"dweb",
17+
"jsonld"
18+
],
19+
"author": "Joel Gustafson",
20+
"license": "MIT",
21+
"bugs": {
22+
"url": "https://github.com/joeltg/jsonld-dweb-loader/issues"
23+
},
24+
"homepage": "https://github.com/joeltg/jsonld-dweb-loader#readme",
25+
"dependencies": {
26+
"cids": "^0.5.5"
27+
}
28+
}

0 commit comments

Comments
 (0)