Source: storage/file/read.js

import { StorageInstance as storage } from '../shared.js';

/**
 * ### Read file from the storage bucket.
 * Returns parsed file content if json flag is set. Otherwise returns string or undefined.
 * **THIS METHOD DOESNT THROW ANY EXCEPTIONS EXTERNALLY**
 * @method module:cpb-storage/file.read
 * @async
 * @param {?string} [bucket=process.env.BUCKET || 'custom-product-builder'] - storage bucket
 * @param {!string} name - file path within bucket
 * @param {?*} [json=true] - return content as json object
 * @param {?number} generation - file version generation to read
 * @returns {Promise<string|object|undefined>} contents - file contents as string or json
 * @throws {TypeError<bucket>}
 * @throws {TypeError<name>}
 * @throws {TypeError<result>}
 */
export default async function ReadFile({ bucket = process.env.BUCKET || 'custom-product-builder', name, json = true, generation } = {}) {
  if (!bucket) throw new TypeError('[cpb-storage/file/read]!bucket');
  if (!name) throw new TypeError('[cpb-storage/file/read]!name');

  const dir = name.split('/').shift();
  // Downloads the file into a buffer in memory.
  const downloadIntoMemory = async () => {
    let contents;
    try {
      contents = await storage.bucket(bucket).file(name, { generation }).download();
    } catch (error) {
      console.error('[cpb-storage/file/read] ReadFile.downloadIntoMemory', { name, generation, bucket, json, error });
      return undefined;
    }
    try {
      if (json) {
        const result = JSON.parse(contents.toString());
        if (!result) throw new TypeError('[cpb-storage/file/read] ReadFile::!result');

        result._file = {
          dir,
          name,
          bucket,
          generation,
          gs: `gs://${bucket}/${name}`,
          url: generation ? `https://storage.googleapis.com/${bucket}/${name}?generation=${generation}` : `https://storage.googleapis.com/${bucket}/${name}`,
        };

        return result;
      }
      return contents.toString();
    } catch (error) {
      console.error('[cpb-storage/file/read] !parseJSON', { error, name, bucket, json, generation });
      return undefined;
    }
  };

  return await downloadIntoMemory().catch(onDownloadIntoMemoryError);

  function onDownloadIntoMemoryError(error) {
    throw error;
  }
}