-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
80 lines (69 loc) · 1.79 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/// <reference path="typings/main.d.ts"/>
import * as isIpfs from 'is-ipfs';
import * as CID from 'cids';
import { Buffer } from 'safe-buffer';
export default class IpfsApiHelper {
public ipfsApi: any;
// default options for storing DAG nodes
public _dagOptions = {};
/**
* Requires an instance of ipfs-http-client or js-ipfs
* @param provider
*/
constructor (provider: any) {
this.ipfsApi = provider;
}
/**
* Transform js object to Buffer instance
* @param data
* @returns {Buffer}
*/
public static toDataBuffer (data: object) {
if (IpfsApiHelper.Buffer.isBuffer(data)) {
return data;
}
return IpfsApiHelper.Buffer.from(JSON.stringify(data));
}
public static get isIpfs () {
return isIpfs;
}
public static get Buffer () {
return Buffer;
}
/**
* Create a node for the `data`
* @param data
*/
public async add (data: object) {
return await this.ipfsApi.dag.put(data, this._dagOptions);
}
/**
* Read data from IPFS path
* @param cid
* @param path
*/
public async get (cid: string | object, path: string) {
return await this.ipfsApi.dag.get(cid, path);
}
/**
* Creates a node from `data` and references it in a link
* @param data
* @param name
*/
public async addLinkFrom (data: object, name: string) {
const cid = await this.add(data);
return await this.addLink(cid, name);
}
/**
* Creates a node with a property linked to a CID
* @param cid
* @param name
*/
public async addLink (cid: string | object, name: string) {
const linkedCid = (typeof cid === 'string' || cid instanceof String) ? new CID(cid) : cid;
if (!CID.isCID(linkedCid)) {
throw new Error('Supplied CID is not valid');
}
return await this.add({ [name]: linkedCid });
}
}