put.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. error: {},
  22. strict: {}
  23. })
  24. module.exports = putData
  25. function putData (cache, key, data, opts) {
  26. opts = PutOpts(opts)
  27. return write(cache, data, opts).then(res => {
  28. return index.insert(
  29. cache, key, res.integrity, opts.concat({ size: res.size })
  30. ).then(entry => {
  31. if (opts.memoize) {
  32. memo.put(cache, entry, data, opts)
  33. }
  34. return res.integrity
  35. })
  36. })
  37. }
  38. module.exports.stream = putStream
  39. function putStream (cache, key, opts) {
  40. opts = PutOpts(opts)
  41. let integrity
  42. let size
  43. const contentStream = write.stream(
  44. cache, opts
  45. ).on('integrity', int => {
  46. integrity = int
  47. }).on('size', s => {
  48. size = s
  49. })
  50. let memoData
  51. let memoTotal = 0
  52. const stream = to((chunk, enc, cb) => {
  53. contentStream.write(chunk, enc, () => {
  54. if (opts.memoize) {
  55. if (!memoData) { memoData = [] }
  56. memoData.push(chunk)
  57. memoTotal += chunk.length
  58. }
  59. cb()
  60. })
  61. }, cb => {
  62. contentStream.end(() => {
  63. index.insert(cache, key, integrity, opts.concat({ size })).then(entry => {
  64. if (opts.memoize) {
  65. memo.put(cache, entry, Buffer.concat(memoData, memoTotal), opts)
  66. }
  67. stream.emit('integrity', integrity)
  68. cb()
  69. })
  70. })
  71. })
  72. let erred = false
  73. stream.once('error', err => {
  74. if (erred) { return }
  75. erred = true
  76. contentStream.emit('error', err)
  77. })
  78. contentStream.once('error', err => {
  79. if (erred) { return }
  80. erred = true
  81. stream.emit('error', err)
  82. })
  83. return stream
  84. }