-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
45 lines (38 loc) · 852 Bytes
/
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
'use strict'
const toPull = require('stream-to-pull-stream')
module.exports = fs
function fs(GridFSBucket, db, options) {
const bucket = new GridFSBucket(db, options)
return {write, read, stat, exists}
function write(id, meta = {}) {
return (read) => {
const stream = bucket.openUploadStreamWithId(id, meta.name, {
metadata: meta,
contentType: meta.type,
})
return new Promise((rs, rj) =>
toPull.sink(stream, (err) => (err ? rj(err) : rs()))(read)
)
}
}
function read(id) {
return toPull.source(bucket.openDownloadStream(id))
}
function stat(id) {
return bucket
.find({_id: id})
.limit(1)
.next()
.then((file) =>
file === null
? null
: {
id: file._id,
meta: file.metadata,
}
)
}
function exists(id) {
return stat(id).then((stat) => stat !== null)
}
}