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

@codercito/object-storage

v0.1.0

Published

Abstracción tipada para object storage (S3-compatible) con CDN URL helpers

Downloads

29

Readme

@codercito/object-storage

Abstracción tipada para object storage compatible con S3 (Amazon S3, Cloudflare R2, MinIO, DigitalOcean Spaces, Backblaze B2) con helpers para construir URLs públicas via CDN.

  • ✅ Subida directa, exists, y presigned POST listos para uso en backend.
  • ✅ Tipado estricto con TypeScript, sin any.
  • ✅ Cero dependencias propias. El AWS SDK es peerDependency (no se duplica).
  • ✅ Sin logs internos: tú decides cómo loggear vía callback onError.
  • ✅ Diseñado para abrirse a otros providers manteniendo la misma interfaz.

Instalación

npm install @codercito/object-storage @aws-sdk/client-s3 @aws-sdk/s3-presigned-post

Los paquetes @aws-sdk/* son peerDependencies: la librería los espera instalados pero no los incluye en su bundle.

Uso básico

import { S3StorageService, CdnFileUrlService } from '@codercito/object-storage';

// Configura el servicio - el consumidor decide de dónde vienen los valores
const storage = new S3StorageService({
    bucket: process.env.S3_BUCKET!,
    region: process.env.S3_REGION!,
    accessKeyId: process.env.S3_ACCESS_KEY_ID!,
    secretAccessKey: process.env.S3_SECRET_ACCESS_KEY!,
});

const urls = new CdnFileUrlService(process.env.CDN_PUBLIC_URL!);

// Subir un archivo
await storage.put('avatars/user-123.jpg', buffer, {
    contentType: 'image/jpeg',
    cacheControl: 'public, max-age=31536000',
});

// Verificar existencia
const exists = await storage.exists('avatars/user-123.jpg');

// Construir URL pública
const url = urls.getPublicUrl('avatars/user-123.jpg');
// → https://cdn.miapp.com/avatars/user-123.jpg

Subida directa desde el cliente (presigned POST)

Genera credenciales en el backend para que el cliente suba directamente al storage sin pasar bytes por tu servidor:

// Backend (ej. API route de Next.js)
const presigned = await storage.presignedPost({
    key: `uploads/${userId}/${filename}`,
    contentType: 'image/jpeg',
    maxSizeBytes: 5 * 1024 * 1024,  // 5 MB
    expiresIn: 600,                  // 10 minutos
});

// Devuélvelo al cliente
return Response.json(presigned);
// Cliente (browser)
const formData = new FormData();
Object.entries(presigned.fields).forEach(([k, v]) => formData.append(k, v));
formData.append('file', file);

await fetch(presigned.url, { method: 'POST', body: formData });

Providers compatibles

S3StorageService funciona con cualquier API S3-compatible cambiando el endpoint:

Cloudflare R2

const storage = new S3StorageService({
    bucket: 'my-bucket',
    region: 'auto',
    endpoint: 'https://ACCOUNT_ID.r2.cloudflarestorage.com',
    accessKeyId: process.env.R2_ACCESS_KEY_ID!,
    secretAccessKey: process.env.R2_SECRET_ACCESS_KEY!,
});

MinIO (local development)

const storage = new S3StorageService({
    bucket: 'my-bucket',
    region: 'us-east-1',
    endpoint: 'http://localhost:9000',
    accessKeyId: 'minioadmin',
    secretAccessKey: 'minioadmin',
    forcePathStyle: true,  // necesario para MinIO
});

DigitalOcean Spaces

const storage = new S3StorageService({
    bucket: 'my-space',
    region: 'nyc3',
    endpoint: 'https://nyc3.digitaloceanspaces.com',
    accessKeyId: process.env.DO_SPACES_KEY!,
    secretAccessKey: process.env.DO_SPACES_SECRET!,
});

Manejo de errores

La librería expone tres clases de error:

import {
    StorageUploadError,
    StoragePresignError,
    StorageConfigError,
} from '@codercito/object-storage';

try {
    await storage.put('a.jpg', buffer, { contentType: 'image/jpeg' });
} catch (e) {
    if (e instanceof StorageUploadError) {
        console.error('Falló la subida', e.key, e.cause);
    }
}

StorageConfigError se lanza al construir el servicio si falta algún campo obligatorio.

Logging y observabilidad

La librería no escribe a console por sí sola. Si quieres loggear los errores internos (antes de que se lancen), inyecta un callback onError:

import pino from 'pino';
const logger = pino();

const storage = new S3StorageService({
    bucket: '...', region: '...',
    accessKeyId: '...', secretAccessKey: '...',
    onError: (event) => {
        logger.error({
            operation: event.operation,
            key: event.key,
            cause: event.cause,
        }, 'Storage error');
    },
});

Esto te permite integrar la librería con Pino, Winston, Sentry, Datadog, etc. sin que la librería decida por ti.

Validar variables de entorno

La librería no incluye un validador de env vars: cada proyecto tiene sus propios nombres y convenciones. Aquí un ejemplo con zod que puedes copiar a tu proyecto:

// src/env.ts
import { z } from 'zod';

const schema = z.object({
    S3_BUCKET: z.string().min(1),
    S3_REGION: z.string().default('auto'),
    S3_ENDPOINT: z.string().url().optional(),
    S3_ACCESS_KEY_ID: z.string().min(1),
    S3_SECRET_ACCESS_KEY: z.string().min(1),
    CDN_PUBLIC_URL: z.string().url(),
});

const parsed = schema.safeParse(process.env);
if (!parsed.success) {
    console.error('Invalid env', parsed.error.flatten().fieldErrors);
    throw new Error('Invalid environment variables');
}
export const env = parsed.data;

Y úsalo:

import { env } from './env';
import { S3StorageService } from '@codercito/object-storage';

export const storage = new S3StorageService({
    bucket: env.S3_BUCKET,
    region: env.S3_REGION,
    endpoint: env.S3_ENDPOINT,
    accessKeyId: env.S3_ACCESS_KEY_ID,
    secretAccessKey: env.S3_SECRET_ACCESS_KEY,
});

API

S3StorageService

new S3StorageService(config: S3StorageConfig)

| Campo | Tipo | Requerido | Descripción | |-------|------|-----------|-------------| | bucket | string | ✅ | Nombre del bucket. | | region | string | ✅ | Región AWS o 'auto' para R2. | | accessKeyId | string | ✅ | Credencial. | | secretAccessKey | string | ✅ | Credencial. | | endpoint | string | — | Endpoint custom (R2, MinIO, etc.). | | forcePathStyle | boolean | — | Necesario para MinIO. | | onError | (event) => void | — | Callback de errores internos. |

put(key, body, options): Promise<void>

Sube un objeto. La key se sanea automáticamente.

options extiende PutObjectCommandInput del AWS SDK; los campos contentType y cacheControl se traducen a sus equivalentes (ContentType, CacheControl).

exists(key): Promise<boolean>

Devuelve true si el objeto existe. false en cualquier otro caso (incluye errores de red).

presignedPost(request): Promise<PresignedPostResult>

Genera credenciales para subida directa desde el cliente.

| Campo | Default | Descripción | |-------|---------|-------------| | key | — | Path destino. | | contentType | — | MIME esperado, se valida en el POST. | | maxSizeBytes | 10485760 (10 MB) | Tamaño máximo permitido. | | expiresIn | 600 (10 min) | Validez en segundos. |

CdnFileUrlService

new CdnFileUrlService(baseUrl: string)

Construye URLs públicas concatenando baseUrl con la key. No re-sanitiza la key — debes pasar la misma con la que subiste el objeto.

const urls = new CdnFileUrlService('https://cdn.miapp.com');
urls.getPublicUrl('avatars/user.jpg');
// → 'https://cdn.miapp.com/avatars/user.jpg'

sanitizeKey(key): string

Normaliza una key:

  • Quita caracteres no permitidos (deja [a-zA-Z0-9/_\-.]).
  • Colapsa slashes duplicados.
  • Quita slashes al inicio y final.
sanitizeKey('/avatars//user 123!.jpg');
// → 'avatars/user123.jpg'

Tipos

Todos los tipos están exportados:

import type {
    IStorageService,
    IFileUrlService,
    S3StorageConfig,
    PutObjectOptions,
    PresignedPostRequest,
    PresignedPostResult,
    StorageErrorEvent,
} from '@codercito/object-storage';

IStorageService es la interfaz principal; útil para inyectar implementaciones distintas (mocks en tests, etc.).

Licencia

MIT