-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
84 lines (65 loc) · 2.11 KB
/
index.js
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
81
82
83
84
const hyperdrive = require('hyperdrive')
const callbackMethods = require('./callback-methods')
const kHyperdrive = Symbol('hyperdrive')
const getHyperdrive = drive => drive[kHyperdrive]
class HyperdrivePromise {
constructor (...args) {
let drive
if (args.length === 1 && args[0].readFile) {
drive = args[0]
} else {
drive = hyperdrive(...args)
}
this._cache = {}
this._createDiffStream.bind(this)
this._checkout.bind(this)
return new Proxy(drive, this)
}
get (target, propKey) {
if (propKey === kHyperdrive) return target
if (propKey === 'createDiffStream') return this._createDiffStream
if (propKey === 'checkout') return this._checkout
const value = Reflect.get(target, propKey)
if (typeof value === 'function') return this._getMethod(target, propKey, value)
return value
}
_getMethod (target, propKey, func) {
let method = this._cache[propKey]
if (method) return method
if (callbackMethods.includes(propKey)) {
method = (...args) => {
// We keep suporting the callback style if we get a callback.
if (typeof args[args.length - 1] === 'function') {
return Reflect.apply(func, target, args)
}
return new Promise((resolve, reject) => {
args.push((err, ...result) => {
if (err) return reject(err)
if (result.length > 1) {
resolve(result)
} else {
resolve(result[0])
}
})
Reflect.apply(func, target, args)
})
}
} else {
method = (...args) => Reflect.apply(func, target, args)
}
this._cache[propKey] = method
return method
}
_createDiffStream (other, prefix, opts) {
if (other instanceof HyperdrivePromise) {
other = getHyperdrive(other)
}
return getHyperdrive(this).createDiffStream(other, prefix, opts)
}
_checkout (version, opts) {
const h = getHyperdrive(this).checkout(version, opts)
return new HyperdrivePromise(h)
}
}
module.exports = (...args) => new HyperdrivePromise(...args)
module.exports.getHyperdrive = getHyperdrive