Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

put.js 1.9KB

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