put.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. 'use strict'
  2. const index = require('./lib/entry-index')
  3. const memo = require('./lib/memoization')
  4. const write = require('./lib/content/write')
  5. const Flush = require('minipass-flush')
  6. const { PassThrough } = require('minipass-collect')
  7. const Pipeline = require('minipass-pipeline')
  8. const putOpts = (opts) => ({
  9. algorithms: ['sha512'],
  10. ...opts,
  11. })
  12. module.exports = putData
  13. function putData (cache, key, data, opts = {}) {
  14. const { memoize } = opts
  15. opts = putOpts(opts)
  16. return write(cache, data, opts).then((res) => {
  17. return index
  18. .insert(cache, key, res.integrity, { ...opts, size: res.size })
  19. .then((entry) => {
  20. if (memoize)
  21. memo.put(cache, entry, data, opts)
  22. return res.integrity
  23. })
  24. })
  25. }
  26. module.exports.stream = putStream
  27. function putStream (cache, key, opts = {}) {
  28. const { memoize } = opts
  29. opts = putOpts(opts)
  30. let integrity
  31. let size
  32. let memoData
  33. const pipeline = new Pipeline()
  34. // first item in the pipeline is the memoizer, because we need
  35. // that to end first and get the collected data.
  36. if (memoize) {
  37. const memoizer = new PassThrough().on('collect', data => {
  38. memoData = data
  39. })
  40. pipeline.push(memoizer)
  41. }
  42. // contentStream is a write-only, not a passthrough
  43. // no data comes out of it.
  44. const contentStream = write.stream(cache, opts)
  45. .on('integrity', (int) => {
  46. integrity = int
  47. })
  48. .on('size', (s) => {
  49. size = s
  50. })
  51. pipeline.push(contentStream)
  52. // last but not least, we write the index and emit hash and size,
  53. // and memoize if we're doing that
  54. pipeline.push(new Flush({
  55. flush () {
  56. return index
  57. .insert(cache, key, integrity, { ...opts, size })
  58. .then((entry) => {
  59. if (memoize && memoData)
  60. memo.put(cache, entry, memoData, opts)
  61. if (integrity)
  62. pipeline.emit('integrity', integrity)
  63. if (size)
  64. pipeline.emit('size', size)
  65. })
  66. },
  67. }))
  68. return pipeline
  69. }