All files / app/storage storage.js

31.25% Statements 5/16
100% Branches 0/0
0% Functions 0/5
31.25% Lines 5/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53    1x 1x 1x   1x                                                                                   1x        
// Google Cloud Storage helpers (upload + signed download URL).
// Authenticates automatically via GOOGLE_APPLICATION_CREDENTIALS.
const { Storage } = require('@google-cloud/storage');
const moment = require('moment');
const config = require('../config');
 
const storage = new Storage({ projectId: config.projectId });
 
// Part IV - Store the zip in GCS with the given object name.
function uploadBuffer(objectName, buffer, contentType) {
  const file = storage.bucket(config.storageBucket).file(objectName);
 
  const stream = file.createWriteStream({
    metadata: {
      contentType,
      cacheControl: 'private'
    },
    resumable: false
  });
 
  return new Promise((resolve, reject) => {
    stream.on('error', err => {
      reject(err);
    });
 
    stream.on('finish', () => {
      resolve('Ok');
    });
 
    stream.end(buffer);
  });
}
 
// Part V - Generate a temporary (2 days) signed download URL for the zip.
async function getDownloadUrl(objectName) {
  const options = {
    action: 'read',
    expires: moment().add(2, 'days').unix() * 1000
  };
 
  const signedUrls = await storage
    .bucket(config.storageBucket)
    .file(objectName)
    .getSignedUrl(options);
 
  return signedUrls[0];
}
 
module.exports = {
  uploadBuffer,
  getDownloadUrl
};