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

@hemia/common

v0.0.2

Published

Paquete común para proyectos de Hemia

Downloads

215

Readme

@hemia/common

Sistema de decoradores y utilidades para crear controladores HTTP con TypeScript usando metadata reflection.


📦 Instalación

npm install @hemia/common reflect-metadata

Nota: Este paquete requiere reflect-metadata como dependencia peer.


🚀 Características

  • ✨ Decoradores para controladores HTTP estilo Express/NestJS
  • 🎯 Soporte completo para métodos HTTP (GET, POST, PUT, DELETE, PATCH, OPTIONS, HEAD)
  • 📝 Decoradores de parámetros para request, response, body, query, params, headers, etc.
  • 🔄 Manejo de redirecciones y headers personalizados
  • 🛡️ Type-safe con TypeScript
  • 📦 Metadata reflection con reflect-metadata

📖 Uso

Configuración inicial

Asegúrate de importar reflect-metadata al inicio de tu aplicación:

import 'reflect-metadata';

También necesitas habilitar los siguientes flags en tu tsconfig.json:

{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  }
}

Ejemplo básico

import { Controller, Get, Post, Body, Param, Query } from '@hemia/common';

@Controller('/users')
class UserController {
  @Get('/')
  getAllUsers(@Query('page') page: string) {
    // Maneja GET /users?page=1
    return { users: [], page };
  }

  @Get('/:id')
  getUserById(@Param('id') id: string) {
    // Maneja GET /users/123
    return { id, name: 'John Doe' };
  }

  @Post('/')
  createUser(@Body() userData: any) {
    // Maneja POST /users
    return { created: true, data: userData };
  }
}

🎨 API Reference

Decoradores de Clase

@Controller(basePath?: string)

Define una clase como controlador HTTP con una ruta base opcional.

@Controller('/api/v1')
class ApiController {
  // ...
}

Decoradores de Método (HTTP)

Los siguientes decoradores definen rutas y métodos HTTP:

  • @Get(path?: string) - Método GET
  • @Post(path?: string) - Método POST
  • @Put(path?: string) - Método PUT
  • @Delete(path?: string) - Método DELETE
  • @Patch(path?: string) - Método PATCH
  • @Options(path?: string) - Método OPTIONS
  • @Head(path?: string) - Método HEAD
@Controller('/products')
class ProductController {
  @Get('/')
  findAll() { /* ... */ }

  @Post('/create')
  create() { /* ... */ }

  @Put('/:id')
  update() { /* ... */ }

  @Delete('/:id')
  remove() { /* ... */ }
}

Decoradores de Parámetros

Extraen información de la petición HTTP:

@Request() / @Req()

Inyecta el objeto request completo.

@Get('/')
handler(@Request() req: any) {
  // Acceso al request completo
}

@Response() / @Res()

Inyecta el objeto response completo.

@Get('/')
handler(@Response() res: any) {
  // Acceso al response completo
}

@Body(key?: string)

Extrae el cuerpo de la petición o una propiedad específica.

@Post('/')
create(@Body() data: any) { /* ... */ }

@Post('/')
create(@Body('email') email: string) { /* ... */ }

@Param(key?: string)

Extrae parámetros de ruta.

@Get('/:id/:name')
handler(@Param('id') id: string, @Param('name') name: string) { /* ... */ }

@Query(key?: string)

Extrae parámetros de query string.

@Get('/')
search(@Query('q') searchTerm: string, @Query('limit') limit: string) { /* ... */ }

@Headers(key?: string)

Extrae headers de la petición.

@Get('/')
handler(@Headers('authorization') auth: string) { /* ... */ }

@Session()

Inyecta el objeto de sesión.

@Get('/profile')
getProfile(@Session() session: any) { /* ... */ }

@Ip()

Obtiene la dirección IP del cliente.

@Get('/')
handler(@Ip() ip: string) { /* ... */ }

@Host()

Obtiene el host de la petición.

@Get('/')
handler(@Host() host: string) { /* ... */ }

@Next()

Inyecta la función next (para middleware).

@Get('/')
handler(@Next() next: Function) { /* ... */ }

Decoradores de Respuesta

@Header(name: string, value: string)

Define headers personalizados para la respuesta.

@Get('/')
@Header('X-Custom-Header', 'value')
@Header('Cache-Control', 'no-cache')
handler() {
  return { data: 'example' };
}

@Redirect(url: string, statusCode?: number)

Redirige a una URL específica (código por defecto: 302).

@Get('/old-page')
@Redirect('/new-page', 301)
redirectHandler() {
  // Redirige permanentemente
}

@Get('/external')
@Redirect('https://example.com')
externalRedirect() {
  // Redirige temporalmente
}

🔍 Metadata Keys

El paquete utiliza las siguientes claves de metadata:

const METADATA_KEYS = {
  BASE_PATH: 'base_path',      // Ruta base del controlador
  ROUTES: 'routes',            // Rutas definidas
  PARAMS: 'params',            // Parámetros del método
  HEADERS: 'headers',          // Headers personalizados
  REDIRECT: 'redirect'         // Configuración de redirección
}

🧪 Desarrollo

Scripts disponibles

| Script | Descripción | |-----------------------|---------------------------------------| | npm run build | Compila el paquete con Rollup | | npm run test | Ejecuta pruebas con Jest | | npm run test:watch | Ejecuta pruebas en modo watch | | npm run test:coverage | Genera reporte de cobertura | | npm run clean | Limpia la carpeta dist/ |

Archivos generados

  • dist/hemia-common.js - Bundle CommonJS
  • dist/hemia-common.esm.js - Bundle ES Module
  • dist/types/ - Declaraciones de TypeScript

📄 Licencia

ISC


✨ Generado con Hemia CLI

Este paquete fue generado usando Hemia CLI.