Solved using Loopback Remote Methods, Streams and Crypto (from node api)
REST API
http://127.0.0.1:3000/api/containers/container1/hash/file.pdf
JSON RESPONSE
{"result":{"container":"container1","filename":"file.pdf","sha256":"29b887311cdce9f21be850e41e44393fa25c11e79cd20457acdb7cbad35ff6c1"}}
models/container.js
var crypto = require("crypto");
module.exports = function (Container) {
Container.hash = function (containerId, filename, cb) {
var fileInfo = {
container: containerId, filename: filename
}
var downloadedFileStream;
// Initializing crypto ReadStream using Loopback Storage Component API
downloadedFileStream = Container.downloadStream(containerId, filename, function (err) {
console.log(err);
cb(err, null);
});
// Initializing crypto writeStream, using crypto module from node
var hash = crypto.createHash('sha256');
hash.setEncoding('hex');
// When the Stream ends, send back the hashcode
downloadedFileStream.on('end' , function () {
hash.end();
fileInfo.sha256 = hash.read();
cb(null, fileInfo);
});
// Piping readStream to the WriteStream
downloadedFileStream.pipe(hash);
}
Container.remoteMethod('hash', {
accepts: [{arg: 'containerId', type: 'string', required: true}, {arg: 'filename', type: 'string', required: true},],
returns: {arg: 'result', type: 'string'},
http: {path: '/:containerId/hash/:filename', verb: 'get'}
});
};