0
votes

On my loopback server, the loopback-storage-component is installed. My app use the angular-file-upload module. Both are working fine.

I need to generate a sha256 string of stored files (for example to arquive in the server, to send to the uploader, etc.).

How can I process my file to generate the hash

GET http:myloopbackserver/api/container/container1/hash/file.pdf

which responds with, for example

{
    file: 'file.pdf',
    sda256: 'bf94874852b8093545071e27808f7ef3b48668ffadbfcfbb7599562034dc7708'
}
1

1 Answers

0
votes

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'}
    });

};