wildduck/lib/filehash-stream.js
NickOvt 8730ed58f6
fix(api-attachment): Calculate file content hash when uploading attachment ZMS-172 (#733)
* Added submission api endpoint to api docs generation

* on attachment upload calculate file content hash

* make stream into separate file, refactor

* create stream during the try to store. otherwise getting stuck

* refactor file content hash update

* safer file content hash handling

* refactor code. Fix possible race condition

* refactor function. Pass callback as last function param
2024-09-26 11:56:36 +03:00

38 lines
805 B
JavaScript

'use strict';
const Transform = require('stream').Transform;
const crypto = require('crypto');
class FileHashCalculatorStream extends Transform {
constructor(options) {
super(options);
this.bodyHash = crypto.createHash('sha256');
this.hash = null;
}
updateHash(chunk) {
this.bodyHash.update(chunk);
}
_transform(chunk, encoding, callback) {
if (!chunk || !chunk.length) {
return callback();
}
if (typeof chunk === 'string') {
chunk = Buffer.from(chunk, encoding);
}
this.updateHash(chunk);
this.push(chunk);
callback();
}
_flush(done) {
this.hash = this.bodyHash.digest('base64');
done();
}
}
module.exports = FileHashCalculatorStream;