1
|
'use strict'
|
2
|
|
3
|
const figgyPudding = require('figgy-pudding')
|
4
|
const index = require('./lib/entry-index')
|
5
|
const memo = require('./lib/memoization')
|
6
|
const write = require('./lib/content/write')
|
7
|
const to = require('mississippi').to
|
8
|
|
9
|
const PutOpts = figgyPudding({
|
10
|
algorithms: {
|
11
|
default: ['sha512']
|
12
|
},
|
13
|
integrity: {},
|
14
|
memoize: {},
|
15
|
metadata: {},
|
16
|
pickAlgorithm: {},
|
17
|
size: {},
|
18
|
tmpPrefix: {},
|
19
|
single: {},
|
20
|
sep: {},
|
21
|
error: {},
|
22
|
strict: {}
|
23
|
})
|
24
|
|
25
|
module.exports = putData
|
26
|
function putData (cache, key, data, opts) {
|
27
|
opts = PutOpts(opts)
|
28
|
return write(cache, data, opts).then(res => {
|
29
|
return index.insert(
|
30
|
cache, key, res.integrity, opts.concat({ size: res.size })
|
31
|
).then(entry => {
|
32
|
if (opts.memoize) {
|
33
|
memo.put(cache, entry, data, opts)
|
34
|
}
|
35
|
return res.integrity
|
36
|
})
|
37
|
})
|
38
|
}
|
39
|
|
40
|
module.exports.stream = putStream
|
41
|
function putStream (cache, key, opts) {
|
42
|
opts = PutOpts(opts)
|
43
|
let integrity
|
44
|
let size
|
45
|
const contentStream = write.stream(
|
46
|
cache, opts
|
47
|
).on('integrity', int => {
|
48
|
integrity = int
|
49
|
}).on('size', s => {
|
50
|
size = s
|
51
|
})
|
52
|
let memoData
|
53
|
let memoTotal = 0
|
54
|
const stream = to((chunk, enc, cb) => {
|
55
|
contentStream.write(chunk, enc, () => {
|
56
|
if (opts.memoize) {
|
57
|
if (!memoData) { memoData = [] }
|
58
|
memoData.push(chunk)
|
59
|
memoTotal += chunk.length
|
60
|
}
|
61
|
cb()
|
62
|
})
|
63
|
}, cb => {
|
64
|
contentStream.end(() => {
|
65
|
index.insert(cache, key, integrity, opts.concat({ size })).then(entry => {
|
66
|
if (opts.memoize) {
|
67
|
memo.put(cache, entry, Buffer.concat(memoData, memoTotal), opts)
|
68
|
}
|
69
|
stream.emit('integrity', integrity)
|
70
|
cb()
|
71
|
})
|
72
|
})
|
73
|
})
|
74
|
let erred = false
|
75
|
stream.once('error', err => {
|
76
|
if (erred) { return }
|
77
|
erred = true
|
78
|
contentStream.emit('error', err)
|
79
|
})
|
80
|
contentStream.once('error', err => {
|
81
|
if (erred) { return }
|
82
|
erred = true
|
83
|
stream.emit('error', err)
|
84
|
})
|
85
|
return stream
|
86
|
}
|