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

@groundbrick/storage-service

v1.1.1

Published

Serviço de storage plugável com suporte a múltiplos provedores (Local, S3, GCS, Azure)

Downloads

94

Readme

@groundbrick/storage-service

Serviço de storage plugável e type-safe para Node.js com suporte a múltiplos provedores (Local, S3, GCS, Azure).

🚀 Características

  • Type-Safe: Totalmente tipado com TypeScript
  • Múltiplos Provedores: Local, AWS S3, Google Cloud Storage, Azure (fácil adicionar novos)
  • Interface Única: Mesma API para todos os provedores
  • Zero Vendor Lock-in: Troque de provedor apenas alterando configuração
  • Singleton Pattern: Controle de instância único
  • Pronto para Produção: Testado e otimizado

📦 Instalação

npm install @groundbrick/storage-service

Dependências Opcionais

Para usar S3:

npm install @aws-sdk/client-s3 @aws-sdk/s3-request-presigner

🔧 Uso Básico

Storage Local

import { StorageService } from '@groundbrick/storage-service';

const storage = StorageService.getInstance({
  provider: 'local',
  config: {
    basePath: './uploads',
    baseUrl: 'http://localhost:3000/uploads'
  }
});

// Upload
const result = await storage.upload(
  fileBuffer,
  'pets/123/photo.jpg',
  {
    contentType: 'image/jpeg',
    isPublic: true
  }
);

console.log(result.url); // http://localhost:3000/uploads/pets/123/photo.jpg

AWS S3

import { StorageService } from '@groundbrick/storage-service';

const storage = StorageService.getInstance({
  provider: 's3',
  config: {
    bucket: 'my-bucket',
    region: 'us-east-1',
    accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!
  }
});

const result = await storage.upload(
  fileBuffer,
  'pets/123/photo.jpg',
  {
    contentType: 'image/jpeg',
    metadata: { petId: '123' },
    isPublic: true
  }
);

🎯 API

StorageService

getInstance(config?: StorageConfig): StorageService

Obtém a instância singleton do serviço.

upload(file: Buffer, path: string, options?: UploadOptions): Promise<StorageResult>

Faz upload de um arquivo.

Parâmetros:

  • file: Buffer do arquivo
  • path: Caminho relativo onde salvar
  • options: Opções de upload (contentType, metadata, isPublic)

Retorna: StorageResult com url, path, size e contentType

download(path: string): Promise<Buffer>

Baixa um arquivo.

delete(path: string): Promise<void>

Deleta um arquivo.

getUrl(path: string): Promise<string>

Obtém a URL de um arquivo.

exists(path: string): Promise<boolean>

Verifica se um arquivo existe.

🔌 Provedores Disponíveis

Local

{
  provider: 'local',
  config: {
    basePath: string;    // Caminho físico no servidor
    baseUrl: string;     // URL base para acessar os arquivos
  }
}

AWS S3

{
  provider: 's3',
  config: {
    bucket: string;
    region: string;
    accessKeyId: string;
    secretAccessKey: string;
    endpoint?: string;   // Para S3-compatible services
  }
}

📝 Exemplos Práticos

Integrando com SvelteKit

// src/lib/server/storage.ts
import { StorageService } from '@groundbrick/storage-service';
import { env } from '$env/dynamic/private';

export const storage = StorageService.getInstance({
  provider: env.STORAGE_PROVIDER as any || 'local',
  config: env.STORAGE_PROVIDER === 's3' 
    ? {
        bucket: env.S3_BUCKET!,
        region: env.S3_REGION!,
        accessKeyId: env.S3_ACCESS_KEY_ID!,
        secretAccessKey: env.S3_SECRET_ACCESS_KEY!
      }
    : {
        basePath: './static/uploads',
        baseUrl: '/uploads'
      }
});
// src/routes/api/upload/+server.ts
import { storage } from '$lib/server/storage';
import { json } from '@sveltejs/kit';

export async function POST({ request }) {
  const formData = await request.formData();
  const file = formData.get('file') as File;
  
  const buffer = Buffer.from(await file.arrayBuffer());
  const path = `uploads/${Date.now()}-${file.name}`;
  
  const result = await storage.upload(buffer, path, {
    contentType: file.type,
    isPublic: true
  });
  
  return json(result);
}

Service Layer Pattern

// services/PetPhotoService.ts
import { StorageService } from '@groundbrick/storage-service';

export class PetPhotoService {
  private storage = StorageService.getInstance();

  async uploadPhoto(petId: string, photo: Buffer, mimeType: string) {
    const fileName = `pets/${petId}/${Date.now()}.${this.getExt(mimeType)}`;
    return await this.storage.upload(photo, fileName, {
      contentType: mimeType,
      metadata: { petId },
      isPublic: true
    });
  }

  async deletePhoto(path: string) {
    await this.storage.delete(path);
  }

  private getExt(mimeType: string): string {
    const map: Record = {
      'image/jpeg': 'jpg',
      'image/png': 'png',
      'image/webp': 'webp'
    };
    return map[mimeType] || 'jpg';
  }
}

🧪 Testes

npm test                 # Roda os testes
npm run test:watch      # Modo watch
npm run test:coverage   # Cobertura de testes

🏗️ Desenvolvimento

# Clonar o repositório
git clone https://github.com/groundbrick/storage-service.git
cd storage-service

# Instalar dependências
npm install

# Build
npm run build

# Watch mode
npm run build:watch

📄 Licença

MIT

🤝 Contribuindo

Contribuições são bem-vindas! Por favor:

  1. Fork o projeto
  2. Crie sua feature branch (git checkout -b feature/NovaFeature)
  3. Commit suas mudanças (git commit -m 'Add: nova feature')
  4. Push para a branch (git push origin feature/NovaFeature)
  5. Abra um Pull Request

🗺️ Roadmap

  • [ ] Suporte a Google Cloud Storage
  • [ ] Suporte a Azure Blob Storage
  • [ ] Suporte a Cloudflare R2
  • [ ] Suporte a upload multipart para arquivos grandes
  • [ ] Cache de URLs
  • [ ] Compressão automática de imagens