npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@sonardigital/nestjs-storage

v1.0.9

Published

Modulo NestJS per caricare file su **Google Cloud Storage**.

Readme

@sonardigital/nestjs-storage

Modulo NestJS per caricare file su Google Cloud Storage.

Dopo la configurazione iniziale ottieni subito un endpoint POST /storage funzionante. Opzionalmente puoi iniettare StorageService nei tuoi servizi.


Integrazione nel progetto (passo per passo)

1. Prerequisiti

  • Un'app NestJS già avviata (@nestjs/common, @nestjs/core)
  • Un bucket su Google Cloud Storage
  • Un service account GCP con permesso di scrittura sul bucket

2. Installa il pacchetto e le dipendenze

Nel tuo progetto NestJS (non in questa repo):

npm install @sonardigital/nestjs-storage nestjs-form-data @nestjs/swagger

Se usi Swagger nel progetto, @nestjs/swagger è già presente. nestjs-form-data serve per gestire l'upload multipart.


3. Prepara le credenziali GCP

Scarica il JSON del service account da Google Cloud Console, poi codificalo in base64:

base64 -i service-account.json | tr -d '\n'

Copia l'output: lo userai come variabile d'ambiente.


4. Aggiungi le variabili d'ambiente

Nel file .env del tuo progetto:

GCS_KEY=eyJ0eXBlIjoic2VydmljZV9hY2NvdW50Ii...   # JSON base64 del service account
GCS_BUCKET=mio-bucket-prod
GCS_URL=https://storage.googleapis.com

| Variabile | Cosa mettere | |--------------|--------------| | GCS_KEY | Intero JSON del service account, codificato in base64 | | GCS_BUCKET | Nome del bucket (es. my-app-uploads) | | GCS_URL | URL base GCS. Lascia https://storage.googleapis.com salvo casi particolari |


5. Registra il modulo in AppModule

Apri src/app.module.ts del tuo progetto e aggiungi l'import:

import { Module } from '@nestjs/common';
import { StorageModule } from '@sonardigital/nestjs-storage';

@Module({
  imports: [
    StorageModule.forRoot({
      key: process.env.GCS_KEY,
      bucketName: process.env.GCS_BUCKET,
      bucketUrl: process.env.GCS_URL,
    }),
    // ... altri moduli del tuo progetto
  ],
})
export class AppModule {}

Fatto. Non serve altro codice per usare l'upload via HTTP.


6. Avvia l'app e prova l'upload

npm run start:dev

Con curl

curl -X POST http://localhost:3000/storage \
  -F "files=@./documento.pdf"

Con Postman / Insomnia

  • Metodo: POST
  • URL: http://localhost:3000/storage
  • Body: form-data
  • Campo: files → tipo File → seleziona uno o più file

Dal frontend (JavaScript)

async function uploadFile(file: File) {
  const formData = new FormData();
  formData.append('files', file);

  const res = await fetch('http://localhost:3000/storage', {
    method: 'POST',
    body: formData,
  });

  const uploaded = await res.json();
  console.log(uploaded[0].url); // URL pubblico del file su GCS
}

7. Risposta dell'API

Status: 201 Created

[
  {
    "originalName": "documento.pdf",
    "baseUrl": "https://storage.googleapis.com",
    "bucketName": "mio-bucket-prod",
    "code": "xK9mP2nQ...",
    "url": "https://storage.googleapis.com/mio-bucket-prod/xK9mP2nQ..."
  }
]

Salva code o url nel tuo database se devi referenziare il file in seguito.

| Campo | Uso | |----------------|-----| | url | Link diretto al file (da restituire al client) | | code | Identificativo univoco del file su GCS | | originalName | Nome del file caricato dall'utente |


Usare StorageService in un altro modulo

Se vuoi caricare file da un tuo servizio (es. durante la creazione di un ordine), importa di nuovo il modulo nel modulo feature che ne ha bisogno:

// src/orders/orders.module.ts
import { Module } from '@nestjs/common';
import { StorageModule } from '@sonardigital/nestjs-storage';
import { OrdersService } from './orders.service';

@Module({
  imports: [
    StorageModule.forRoot({
      key: process.env.GCS_KEY,
      bucketName: process.env.GCS_BUCKET,
      bucketUrl: process.env.GCS_URL,
    }),
  ],
  providers: [OrdersService],
})
export class OrdersModule {}

Poi inietta il servizio:

// src/orders/orders.service.ts
import { Injectable } from '@nestjs/common';
import { StorageService } from '@sonardigital/nestjs-storage';
import { MemoryStoredFile } from 'nestjs-form-data';

@Injectable()
export class OrdersService {
  constructor(private readonly storage: StorageService) {}

  async saveAttachment(files: MemoryStoredFile[]) {
    const uploaded = await this.storage.upload({ files });
    return uploaded[0].url;
  }
}

Nota: se nel tuo progetto usi @nestjs/config, puoi leggere le variabili con ConfigService invece di process.env.


Cosa fa il modulo sotto il cofano

Client (form-data)
       │
       ▼
POST /storage  ──►  StorageController
                           │
                           ▼
                    StorageService.upload()
                           │
                           ▼
              Google Cloud Storage (bucket)
                           │
                           ▼
              Risposta JSON con url e code
  1. Riceve uno o più file nel campo files
  2. Genera un nome univoco (code) per ogni file
  3. Scrive il file sul bucket GCS
  4. Restituisce metadati + URL pubblico

Export del pacchetto

import {
  StorageModule,
  StorageService,
  StorageController,
  StorageDto,
  CreateStorageDto,
} from '@sonardigital/nestjs-storage';