A guide on using TypeScript to allow public access to a file within a Google Cloud Storage bucket

Seeking guidance on converting the Javascript code below to TypeScript:

var storage = require('@google-cloud/storage')();
var myBucket = storage.bucket('my-bucket');

var file = myBucket.file('my-file');

file.makePublic(function(err, apiResponse) {});

I attempted the conversion as follows:

import * as storage from '@google-cloud/storage';
const myBucket = storage.Bucket('my-bucket');

const file = myBucket.file('my-file');

file.makePublic(function(err, apiResponse) {});

However, Visual Studio Code is flagging this line (highlighted in bold):

const myBucket = storage.Bucket('my-bucket');

Hovering over the underlined line reveals the following message:

[ts] Value of type 'typeof Bucket' is not callable. Did you mean to include 'new'? class Storage.Bucket

It seems like I need to instantiate the class using the new keyword, but even after making that change, the line remains flagged by Visual Studio Code (bold):

const myBucket = new storage.Bucket('my-bucket');

This time, the error message states:

[ts] Expected 2 arguments, but got 1. constructor Storage.Bucket(storage: storage.Storage, name: string): storage.Bucket

This indicates that two arguments are required - one of type storage and one of type string. While I have the second argument (string type), I am unsure how to create the storage type.

How can I define the first argument (storage type)?

In the original Javascript example, only the second argument (string type) is needed. The Javascript code seems to somehow infer or provide a default value for the storage type. Is there a way to achieve the same in the TypeScript version?

Thank you for your assistance.

Answer №1

storage is being utilized as a function in this scenario:

import * as storage from '@google-cloud/storage'
const myBucket = storage().bucket('my-bucket')

If you find that storage() isn't behaving as expected, consider passing parameters to adjust its behavior. Consult the API documentation for more information.

In addition, you can obtain a storage bucket instance through the Firebase Admin SDK if you're working with Firebase and need to access your project's default storage:

import * as admin from 'firebase-admin'
const myBucket = admin.storage().bucket()

Answer №2

If you need to obtain a public URL from Google Cloud Storage

Follow the clear instructions on GitHub by simply converting the import to TypeScript import

https://github.com/GoogleCloudPlatform/nodejs-getting-started/blob/master/3-binary-data/lib/images.js

import * as Storage from '@google-cloud/storage'
import * as config from '../config';

const CLOUD_BUCKET = config.get('CLOUD_BUCKET');

const storage = Storage({
  projectId: config.get('GCLOUD_PROJECT')
});
const bucket = storage.bucket(CLOUD_BUCKET);
function getPublicUrl (filename) {
  return `https://storage.googleapis.com/${CLOUD_BUCKET}/${filename}`;
}

file.makePublic().then(() => {
  req.file.cloudStoragePublicUrl = getPublicUrl(gcsname);
  next();
});

https://cloud.google.com/nodejs/getting-started/using-cloud-storage

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to delete an element from an array in MongoDB

I am a beginner in the MEAN stack development. I am currently working on implementing this and this. I have been using the $pull method, but it seems that it is not working for me. I suspect that the issue might be due to the differences in my MongoDB stru ...

Vite is turning a blind eye to compiler errors until the specific file is executed during runtime

There's an odd issue with Vite that allows me to log in to my app and use it freely, until I click on a page that triggers a compilation error. Once that happens, the page won't render and the error is displayed in the console. Strangely enough, ...

Vercel keeps storing information in its cache that I prefer to keep uncached

Currently, I am working on a personal project using NextJS 14 with Vercel. During development, the website functions as intended. However, in production, the data is only fetched upon deployment. This results in the data not updating until a new deployment ...

Experiencing an array of issues while attempting to convert my HTTP request into an

I am currently facing some difficulties in converting my HTTP requests into observables. Within my Angular App, there is a service called API Service which takes care of handling all the requests to the backend. Then, for each component, I have a separate ...

DOCKER: Encounter with MongooseError [MongooseServerSelectionError] - Unable to resolve address for mongo

I am currently attempting to establish a connection between MongoDB and my application within a Docker container. Utilizing the mongoose package, here is the code snippet that I have implemented: mongoose.connect("mongodb://mongo:27016/IssueTracker", { us ...

Is there a way to initiate validations for inputs within ReactiveForms?

After creating a form using Reactive Forms, I have implemented functionality for users to set a new password. The process involves entering both the old and new passwords, as well as confirming the new password. Throughout development, I considered the fol ...

Encountering issues during npm installation process

Encountering an issue during my attempt to install TypeScript C:\ESAB_Scripting\H5ScriptSDK\Samples>npm install -g TypeScript npm ERR! code E404 npm ERR! 404 Not Found - GET https://registry.npmjs.org/TypeScript - Not found ...

Deep Dive into TypeScript String Literal Types

Trying to find a solution for implementing TSDocs with a string literal type declaration in TypeScript. For instance: type InputType = /** Comment should also appear for num1 */ 'num1' | /** Would like the TSDoc to be visible for num2 as well ...

Discovering React components within a shadow DOM utilizing TypeScript and Protractor [

I am currently faced with the challenge of locating elements within a shadow root from 9-11. Traditional locators like xpath, css, and id have proven unsuccessful in this scenario. However, I was able to successfully locate the element using JavascriptExec ...

Verify if the date surpasses the current date and time of 17:30

Given a date and time parameters, I am interested in determining whether that date/time is greater than the current date at 17:30. I am hoping to achieve this using moment js. Do you think it's possible? This is what I have been attempting: let ref ...

What is the importance of having a generic Locals type Request in express?

As I was working on creating the properties of a Request object without using global declarations, I encountered a problem that threw me off course. I attempted to utilize the generic Locals for Request in order to set up the req.auth property, but unfort ...

Traversing through JSON objects in Angular 2

I am currently facing an issue while trying to iterate through a JSON object. Below is the sample JSON data: floors.ts this.floors= [ { floorName: "floor 1", result: [ { resFloor: "1", ...

Difficulty with the value binding issue on input text produced by *NgFor

When using *ngFor in Angular to loop over an array and generate input text elements bound to the values in the array, I'm encountering some issues. The value is not binding correctly when a user inputs something into the text field. I attempted to ru ...

Using forEach with switch cases in Angular5 (TypeScript)

I am trying to work with a basic array of languages and a switch function, but I am having trouble using the forEach method on the cases. It would be really helpful as there are numerous languages in the world! ;) public languages = ["en", "de"]; public s ...

The power of Swift combined with Firebase arrays

https://i.sstatic.net/Q1q0W.png I am facing an issue with appending values from JSON data and storing them in an array named 'values'. The goal is to retrieve these values in the 'updateChartValues()' function and add them to a new arr ...

Determine the data type of an index within an array declaration

Imagine we have the following array literal: const list = ['foo', 'bar', 'baz'] as const; We are attempting to create a type that represents potential indices of this array. This is what we tried: const list = ['foo&ap ...

What is the best way to get both the id and name of a selected item in Angular?

Within my select field, data is dynamically populated based on names. My objective is to not only capture the selected name but also its corresponding ID. Here's a snippet of my HTML template: <select class="custom-select d-block w-100" id="test" ...

retrieve the URL for downloading files from Firebase Storage after uploading multiple files

Recently, I've been diving into the world of Firebase and AngularJS, and have run into a hitch when it comes to retrieving download URLs from Firebase Storage and storing them in the Realtime Database. Although I successfully managed to upload multip ...

Error: The specified 'supportedValuesOf' property is not present in the 'Intl' type

My current date-time library is dayJS and I am looking to display a comprehensive list of all available time zones. I attempted to utilize the Intl object for this purpose: Intl.supportedValuesOf("timeZone") However, I encountered a typescr ...

Is there a way to extract data from a single line?

In my code, I have a simple object retrieved like this: getSelectedRecipients(event) { this.aliasesService.getRecipients(event.nr) .subscribe( res => { this.recipients = res; this.isVisible = true; }, err =&g ...