summaryrefslogtreecommitdiff
path: root/deps/npm/node_modules/npm-registry-fetch/node_modules/cacache/put.js
blob: fe1293e5e7c5ae2d59964b3ea79f4ece4a950e81 (plain)
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
'use strict'

const index = require('./lib/entry-index')
const memo = require('./lib/memoization')
const write = require('./lib/content/write')
const to = require('mississippi').to

module.exports = putData
function putData (cache, key, data, opts) {
  opts = opts || {}
  return write(cache, data, opts).then(res => {
    // TODO - stop modifying opts
    opts.size = res.size
    return index.insert(cache, key, res.integrity, opts).then(entry => {
      if (opts.memoize) {
        memo.put(cache, entry, data, opts)
      }
      return res.integrity
    })
  })
}

module.exports.stream = putStream
function putStream (cache, key, opts) {
  opts = opts || {}
  let integrity
  let size
  const contentStream = write.stream(
    cache, opts
  ).on('integrity', int => {
    integrity = int
  }).on('size', s => {
    size = s
  })
  let memoData
  let memoTotal = 0
  const stream = to((chunk, enc, cb) => {
    contentStream.write(chunk, enc, () => {
      if (opts.memoize) {
        if (!memoData) { memoData = [] }
        memoData.push(chunk)
        memoTotal += chunk.length
      }
      cb()
    })
  }, cb => {
    contentStream.end(() => {
      // TODO - stop modifying `opts`
      opts.size = size
      index.insert(cache, key, integrity, opts).then(entry => {
        if (opts.memoize) {
          memo.put(cache, entry, Buffer.concat(memoData, memoTotal), opts)
        }
        stream.emit('integrity', integrity)
        cb()
      })
    })
  })
  let erred = false
  stream.once('error', err => {
    if (erred) { return }
    erred = true
    contentStream.emit('error', err)
  })
  contentStream.once('error', err => {
    if (erred) { return }
    erred = true
    stream.emit('error', err)
  })
  return stream
}