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

@fge-bo-nest/files-v2

v0.0.6

Published

Librería de gestión de archivos V2 para NestJS

Readme

@fge-bo-nest/files-v2

npm

Librería cliente para NestJS que permite interactuar con el microservicio ms-files-v2 (gestión de archivos). Desarrollada por DNTIC - Ministerio Público.


Instalación

yarn add @fge-bo-nest/files-v2
o
npm install @fge-bo-nest/files-v2

Configuración

Registra el módulo en tu AppModule usando MsFilesV2Module.register():

import { MsFilesV2Module } from '@fge-bo-nest/files-v2';

@Module({
  imports: [
    MsFilesV2Module.register({
      url: process.env.ENV_SERVICE_MS_FILES_V2,  // URL base del microservicio
      global: true,                               // opcional, expone el módulo globalmente
      timeout: 15000,                             // opcional, timeout en ms (default: 15000)
      maxBodyLength: 100_000_000,                 // opcional, tamaño máximo del cuerpo
      maxContentLength: 100_000_000,              // opcional, tamaño máximo de contenido
    }),
  ],
})
export class AppModule {}

Opciones de register()

| Opción | Tipo | Requerido | Descripción | |--------------------|-----------|-----------|--------------------------------------------------| | url | string | ✅ | URL base del microservicio ms-files-v2 | | global | boolean | ❌ | Registra el módulo globalmente (default: false) | | timeout | number | ❌ | Timeout de peticiones HTTP en ms (default: 15000) | | maxBodyLength | number | ❌ | Tamaño máximo del body de la petición | | maxContentLength | number | ❌ | Tamaño máximo del contenido de la respuesta |


Uso

Inyecta MsFilesV2Service en tu servicio o controlador. Expone cuatro sub-servicios agrupados por funcionalidad:

import { MsFilesV2Service } from '@fge-bo-nest/files-v2';

@Injectable()
export class MyService {
  constructor(private readonly msFiles: MsFilesV2Service) {}
}

| Propiedad | Tipo | Descripción | |-------------------------|----------------------------|--------------------------------------| | msFiles.files | FilesClientService | Operaciones CRUD de archivos | | msFiles.signedUrl | SignedUrlClientService | Generación y uso de URLs firmadas | | msFiles.compression | CompressionClientService | Compresión de archivos | | msFiles.migration | MigrationClientService | Migración desde ms-files-v1 (Mongo) |

También puedes inyectar directamente cualquiera de los sub-servicios:

import { FilesClientService } from '@fge-bo-nest/files-v2';

@Injectable()
export class MyService {
  constructor(private readonly filesService: FilesClientService) {}
}

FilesClientService

Operaciones principales de gestión de archivos.

uploadFile(file, filename, body)

Sube un único archivo.

const result = await this.msFiles.files.uploadFile(buffer, 'documento.pdf', {
  application: 'mi-app',
  directory: 'documentos',
  user: 'user-id',
  tags: ['contrato'],
  isPublic: false,
  ocrPdf: false,
  compressPdf: true,
});

Parámetros CreateFileInput:

| Campo | Tipo | Requerido | Descripción | |----------------|------------|-----------|---------------------------------------------| | application | string | ✅ | Identificador de la aplicación origen | | directory | string | ✅ | Directorio destino en el NAS | | user | string | ✅ | ID del usuario que sube el archivo | | tags | string[] | ❌ | Etiquetas del archivo | | isPublic | boolean | ❌ | Si el archivo es público | | ocrPdf | boolean | ❌ | Aplica OCR al PDF | | repairPdf | boolean | ❌ | Repara el PDF | | sanitizePdf | boolean | ❌ | Sanitiza el PDF | | compressPdf | boolean | ❌ | Comprime el PDF | | processImg | boolean | ❌ | Procesa la imagen | | convertToWebP| boolean | ❌ | Convierte imagen a WebP | | subDirectory | boolean | ❌ | Usa subdirectorios |


uploadMultiple(files, body)

Sube múltiples archivos en una sola petición.

const result = await this.msFiles.files.uploadMultiple(
  [
    { file: buffer1, filename: 'doc1.pdf' },
    { file: buffer2, filename: 'doc2.pdf' },
  ],
  { application: 'mi-app', directory: 'documentos', user: 'user-id' },
);

findAll()

Obtiene todos los archivos registrados.

const { data } = await this.msFiles.files.findAll();

findOne(id)

Obtiene un archivo por su ID.

const { data } = await this.msFiles.files.findOne('file-id');

findMany(body)

Obtiene múltiples archivos por sus IDs.

const { data } = await this.msFiles.files.findMany({ ids: ['id1', 'id2'] });

update(id, body)

Actualiza los metadatos de un archivo.

const { data } = await this.msFiles.files.update('file-id', {
  isPublic: true,
  tags: ['nuevo-tag'],
});

delete(id, deleteStorage?, deleteDb?)

Elimina un archivo. Por defecto elimina del storage pero no de la base de datos.

await this.msFiles.files.delete('file-id');
// o controlando cada capa:
await this.msFiles.files.delete('file-id', true, false);

| Parámetro | Tipo | Default | Descripción | |-----------------|-----------|---------|--------------------------------------| | id | string | — | ID del archivo | | deleteStorage | boolean | true | Elimina el archivo del NAS | | deleteDb | boolean | false | Elimina el registro de la base de datos |


downloadFile(id, responseType?)

Descarga un archivo como stream o arraybuffer.

const stream = await this.msFiles.files.downloadFile('file-id', 'stream');

replaceFile(file, filename, body)

Reemplaza el contenido de un archivo existente.

await this.msFiles.files.replaceFile(newBuffer, 'nuevo.pdf', {
  fileId: 'file-id',
  user: 'user-id',
});

Parámetros ReplaceFileInput:

| Campo | Tipo | Requerido | Descripción | |------------|------------|-----------|---------------------------| | fileId | string | ✅ | ID del archivo a reemplazar | | user | string | ✅ | ID del usuario | | tags | string[] | ❌ | Nuevas etiquetas | | isPublic | boolean | ❌ | Visibilidad del archivo |


downloadPdfPages(fileId, query, responseType?)

Descarga un rango de páginas de un PDF.

const pdf = await this.msFiles.files.downloadPdfPages('file-id', { start: 1, end: 5 });

SignedUrlClientService

Generación y uso de URLs firmadas (con expiración y control de descargas).

generateSignedUrl(body, xUserIp?)

Genera una URL firmada para descarga segura. El campo xUserIp puede enviarse como cabecera o en el objeto body si se requiere validar la IP del solicitante.

const { data } = await this.msFiles.signedUrl.generateSignedUrl({
  fileId: 'file-id',
  user: 'user-id',
  watermark: false,
  oneTimeDownload: true,
  duration: 60,       // minutos
  quantity: 1,        // descargas permitidas
  restrictUser: true,
  urlByRange: false,
  xUserIp: '192.0.2.1', // opcional
});

Parámetros GenerateUrlFileInput:

| Campo | Tipo | Requerido | Descripción | |-------------------|-----------|-----------|----------------------------------------------| | fileId | string | ✅ | ID del archivo | | user | string | ✅ | ID del usuario | | watermark | boolean | ✅ | Aplica marca de agua al descargar | | oneTimeDownload | boolean | ❌ | URL de un solo uso | | duration | number | ❌ | Duración en minutos | | quantity | number | ❌ | Cantidad de descargas permitidas | | restrictUser | boolean | ❌ | Restringe la descarga al usuario generador | | urlByRange | boolean | ❌ | Genera URL con soporte de rango HTTP | | xUserIp | string | ❌ | (Opcional) IP del usuario para validación |

Respuesta GenerateSignedUrlResponse:

{
  url: string;
  sessionToken?: string;
  expiresAt: string;
}

downloadWithSignedUrl(hash, user, responseType?)

Descarga un archivo usando una URL firmada previamente generada.

const stream = await this.msFiles.signedUrl.downloadWithSignedUrl('hash-value', 'user-id');

CompressionClientService

Compresión de archivos almacenados en el microservicio.

compressOne(body)

Inicia la compresión de un único archivo.

const { data } = await this.msFiles.compression.compressOne({
  fileId: 'file-id',
  user: 'user-id',
  version: 2,  // 1 = ms-files-v1, 2 = ms-files-v2
});

Respuesta CompressionOneResponse:

{
  fileId: string;
  originalSize: number;
  compressedSize: number;
}

compressBatch(body)

Inicia la compresión de un lote de archivos.

const { data } = await this.msFiles.compression.compressBatch({
  user: 'user-id',
  fileIds: ['id1', 'id2', 'id3'],
  version: 2,
});

Respuesta CompressionBatchResponse:

{
  totalArchivos: number;
  mensajesEnviados: number;
  mensajesFallidos: number;
  version: number;
}

MigrationClientService

Migración de archivos desde ms-files-v1 (MongoDB) hacia ms-files-v2.

migrateOneFile(body)

Inicia la migración de un archivo individual desde MongoDB.

const { data } = await this.msFiles.migration.migrateOneFile({
  fileId: 'mongo-file-id',
  user: 'user-id',
  subDirectory: false,
});

migrateDetail(id)

Obtiene el detalle de un archivo migrado.

const { data } = await this.msFiles.migration.migrateDetail('file-id');

Tipos principales exportados

| Tipo | Descripción | |-------------------------------|-----------------------------------------------------| | FileDocumentLite | Representación de un archivo en ms-files-v2 | | UploadMultipleResponseItem | Resultado por archivo en una subida múltiple | | GenerateSignedUrlResponse | Respuesta de generación de URL firmada | | CompressionOneResponse | Resultado de compresión de un archivo | | CompressionBatchResponse | Resultado de compresión en lote | | MigrationFromMongoResponse | Resultado de una migración desde Mongo | | MigrateFileDetailResponse | Detalle de un archivo migrado |


Links