Limit the number of downloads

Viewed 483

i´m really new using mongoDB and node.js, im trying to limit the number of download per file in my server. i´m using gridfs to storage the file on the data base and after generate a link to be able to download the file i need to limit number of download for each file but have no idea how to do it.

1 Answers

Let say you are using express as your node.js http server, you could do something like that :

const app = require('express')();
const bucket = new mongodb.GridFSBucket(db, {
  chunkSizeBytes: 1024,
  bucketName: 'songs'
});

const downloads = {};

const fileURI = '/somefile.mp3';
const maxDownload = 100;

app.get(fileURI, function(req, res) {
  if (downloads[fileURI] <= maxDownload) {
      // pipe the file to res
      return bucket.openDownloadStreamByName('somefile.mp3').
      .pipe(res)
      .on('error', function(error) {
          console.error(error);
      })
      .on('finish', function() {
          console.log('done!');
          downloads[fileURI] = downloads[fileURI] || 0;
          downloads[fileURI]++;
      });
    } 

    return res.status(400).send({ message: 'download limit reached' });
});    

app.listen(8080);
Related