put.js 1.9 KB

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