put.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. }
  23. return res.integrity
  24. })
  25. })
  26. }
  27. module.exports.stream = putStream
  28. function putStream (cache, key, opts = {}) {
  29. const { memoize } = opts
  30. opts = putOpts(opts)
  31. let integrity
  32. let size
  33. let memoData
  34. const pipeline = new Pipeline()
  35. // first item in the pipeline is the memoizer, because we need
  36. // that to end first and get the collected data.
  37. if (memoize) {
  38. const memoizer = new PassThrough().on('collect', data => {
  39. memoData = data
  40. })
  41. pipeline.push(memoizer)
  42. }
  43. // contentStream is a write-only, not a passthrough
  44. // no data comes out of it.
  45. const contentStream = write.stream(cache, opts)
  46. .on('integrity', (int) => {
  47. integrity = int
  48. })
  49. .on('size', (s) => {
  50. size = s
  51. })
  52. pipeline.push(contentStream)
  53. // last but not least, we write the index and emit hash and size,
  54. // and memoize if we're doing that
  55. pipeline.push(new Flush({
  56. flush () {
  57. return index
  58. .insert(cache, key, integrity, { ...opts, size })
  59. .then((entry) => {
  60. if (memoize && memoData) {
  61. memo.put(cache, entry, memoData, opts)
  62. }
  63. if (integrity) {
  64. pipeline.emit('integrity', integrity)
  65. }
  66. if (size) {
  67. pipeline.emit('size', size)
  68. }
  69. })
  70. }
  71. }))
  72. return pipeline
  73. }