3
3
const Promise = require ( 'bluebird' )
4
4
5
5
const index = require ( './lib/entry-index' )
6
+ const memo = require ( './lib/memoization' )
6
7
const pipe = Promise . promisify ( require ( 'mississippi' ) . pipe )
7
8
const putContent = require ( './lib/content/put-stream' )
8
9
const through = require ( 'mississippi' ) . through
9
10
const to = require ( 'mississippi' ) . to
10
11
11
12
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 ) {
17
14
opts = opts || { }
18
15
const src = through ( )
19
- let meta
16
+ let digest
20
17
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 ( ) )
26
21
return ret
27
22
}
28
23
@@ -33,26 +28,37 @@ function putStream (cache, key, opts) {
33
28
const contentStream = putContent ( cache , opts ) . on ( 'digest' , function ( d ) {
34
29
digest = d
35
30
} )
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 ( ( ) => {
41
44
index . insert ( cache , key , digest , opts ) . then ( entry => {
45
+ if ( opts . memoize ) {
46
+ memo . put ( cache , entry , Buffer . concat ( memoData , memoTotal ) )
47
+ }
42
48
stream . emit ( 'digest' , digest )
43
- stream . emit ( 'metadata' , entry )
44
49
cb ( )
45
50
} )
46
51
} )
47
52
} )
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
51
57
contentStream . emit ( 'error' , err )
52
58
} )
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
56
62
stream . emit ( 'error' , err )
57
63
} )
58
64
return stream
0 commit comments