Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit b613a70

Browse files
committedMar 2, 2017
feat(put): added memoization support to put
1 parent 4205cf0 commit b613a70

File tree

1 file changed

+29
-23
lines changed

1 file changed

+29
-23
lines changed
 

Diff for: ‎put.js

+29-23
Original file line numberDiff line numberDiff line change
@@ -3,26 +3,21 @@
33
const Promise = require('bluebird')
44

55
const index = require('./lib/entry-index')
6+
const memo = require('./lib/memoization')
67
const pipe = Promise.promisify(require('mississippi').pipe)
78
const putContent = require('./lib/content/put-stream')
89
const through = require('mississippi').through
910
const to = require('mississippi').to
1011

1112
module.exports = putData
12-
function putData (cache, key, data, opts, cb) {
13-
if (!cb) {
14-
cb = opts
15-
opts = null
16-
}
13+
function putData (cache, key, data, opts) {
1714
opts = opts || {}
1815
const src = through()
19-
let meta
16+
let digest
2017
const dest = putStream(cache, key, opts)
21-
dest.on('metadata', function (m) { meta = m })
22-
const ret = pipe(src, dest).then(() => meta)
23-
src.write(data, function () {
24-
src.end()
25-
})
18+
dest.on('digest', d => { digest = d })
19+
const ret = pipe(src, dest).then(() => digest)
20+
src.write(data, () => src.end())
2621
return ret
2722
}
2823

@@ -33,26 +28,37 @@ function putStream (cache, key, opts) {
3328
const contentStream = putContent(cache, opts).on('digest', function (d) {
3429
digest = d
3530
})
36-
let errored = false
37-
const stream = to(function (chunk, enc, cb) {
38-
contentStream.write(chunk, enc, cb)
39-
}, function (cb) {
40-
contentStream.end(function () {
31+
let memoData
32+
let memoTotal = 0
33+
const stream = to((chunk, enc, cb) => {
34+
contentStream.write(chunk, enc, () => {
35+
if (opts.memoize) {
36+
if (!memoData) { memoData = [] }
37+
memoData.push(chunk)
38+
memoTotal += chunk.length
39+
}
40+
cb()
41+
})
42+
}, cb => {
43+
contentStream.end(() => {
4144
index.insert(cache, key, digest, opts).then(entry => {
45+
if (opts.memoize) {
46+
memo.put(cache, entry, Buffer.concat(memoData, memoTotal))
47+
}
4248
stream.emit('digest', digest)
43-
stream.emit('metadata', entry)
4449
cb()
4550
})
4651
})
4752
})
48-
stream.on('error', function (err) {
49-
if (errored) { return }
50-
errored = true
53+
let erred = false
54+
stream.once('error', err => {
55+
if (erred) { return }
56+
erred = true
5157
contentStream.emit('error', err)
5258
})
53-
contentStream.on('error', function (err) {
54-
if (errored) { return }
55-
errored = true
59+
contentStream.once('error', err => {
60+
if (erred) { return }
61+
erred = true
5662
stream.emit('error', err)
5763
})
5864
return stream

0 commit comments

Comments
 (0)
Failed to load comments.