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

@jamx-framework/adapter-lambda

v1.0.0

Published

JAMX Framework — AWS Lambda adapter

Readme

@jamx-framework/adapter-lambda

Descripción

Adaptador de JAMX Framework para AWS Lambda. Permite ejecutar handlers de JAMX como funciones serverless en AWS Lambda, manejando la conversión entre eventos de Lambda y el modelo de request/response de JAMX, incluyendo soporte para API Gateway y otros triggers.

Cómo funciona

El adaptador convierte eventos de Lambda (típicamente de API Gateway) en JamxRequest, ejecuta el handler de JAMX y luego convierte la respuesta en un formato compatible con Lambda (objeto con statusCode, headers y body). Maneja automáticamente:

  • Parsing de JSON en el body
  • Query strings y path parameters
  • Headers HTTP
  • CORS (si está configurado)
  • Errores y excepciones

Componentes principales

  • src/adapter.ts: Función createLambdaHandler que adapta un handler de JAMX a Lambda
  • src/index.ts: Punto de exportación
  • src/types.ts: Tipos específicos para Lambda (APIGatewayProxyEvent, etc.)

Uso básico

// lambda.ts
import { createLambdaHandler } from '@jamx-framework/adapter-lambda';

const handler = createLambdaHandler(async (req, res) => {
  res.json({ message: 'Hello from JAMX on AWS Lambda!' });
});

export { handler };

Con API Gateway

export const apiHandler = createLambdaHandler(async (req, res) => {
  const { id } = req.params;
  const user = await db.users.findById(id);
  
  if (!user) {
    res.notFound('User not found');
    return;
  }
  
  res.json({ user });
});

Ejemplos

Manejo de path parameters

export const handler = createLambdaHandler(async (req, res) => {
  // API Gateway v2: params están en req.params
  const userId = req.params['userId'] ?? req.params['id'];
  
  if (!userId) {
    res.badRequest('Missing user ID');
    return;
  }
  
  const user = await getUser(userId);
  res.json({ user });
});

Query strings

export const handler = createLambdaHandler(async (req, res) => {
  const page = parseInt(req.query['page'] ?? '1');
  const limit = parseInt(req.query['limit'] ?? '10');
  
  const users = await db.users.findAll({ page, limit });
  res.json({ users, page, limit });
});

Middleware de logging

const withLogging = createLambdaHandler(async (req, res, next) => {
  console.log(`[${new Date().toISOString()}] ${req.method} ${req.path}`);
  next();
});

export { withLogging };

Flujo interno

  1. Event parsing: El adaptador recibe un evento de Lambda (APIGatewayProxyEvent o similar).
  2. toJamxRequest: Convierte el evento en JamxRequest extrayendo método, path, headers, query params y body.
  3. Handler execution: Ejecuta el handler de JAMX con la request y un ResponseBuilder.
  4. toLambdaResponse: Convierte el ResponseBuilder en un objeto compatible con Lambda ({ statusCode, headers, body }).
  5. Return: Retorna el objeto de respuesta a Lambda, que API Gateway serializa como HTTP response.

API Reference

createLambdaHandler

(handler: JamxHandler) => (event: APIGatewayProxyEvent, context: Context) => Promise<APIGatewayProxyResult>

Crea un handler de Lambda que ejecuta un handler de JAMX.

Tipos soportados

  • APIGatewayProxyEvent (API Gateway REST API)
  • APIGatewayProxyEventV2 (API Gateway HTTP API)
  • SNSEvent, SQSEvent, etc. (otros triggers)

Performance Considerations

  • Cold start minimizado: El handler se inicializa una vez y se reutiliza entre invocaciones.
  • Body parsing: JSON se parsea automáticamente; otros formatos se dejan como string.
  • Header normalization: Los headers se convierten a lowercase para consistencia.
  • Error handling: Excepciones no capturadas se convierten en respuestas 500 con mensaje genérico.

Configuration Options

// Configuración opcional del adaptador
const handler = createLambdaHandler(jamxHandler, {
  // Si true, parsea automáticamente JSON en el body (default: true)
  parseJsonBody: true,
  
  // Headers que se deben excluir de la request (ej: headers de Lambda)
  excludedHeaders: ['x-amzn-trace-id'],
  
  // Si true, habilita CORS automático para OPTIONS requests
  cors: true,
  
  // Orígenes permitidos para CORS
  corsOrigins: ['*'],
});

Testing

Tests en packages/adapter-lambda/tests/unit/adapter.test.ts:

pnpm test

Cubre:

  • Conversión de eventos API Gateway a JamxRequest
  • Extracción de path parameters, query strings, headers
  • Parsing de JSON body
  • Construcción de respuestas Lambda
  • Manejo de errores

Compatibility

  • Compatible con AWS Lambda (Node.js 18.x, 20.x)
  • Funciona con API Gateway (REST y HTTP APIs)
  • Soporta otros triggers (SNS, SQS, etc.) con adaptación personalizada
  • No requiere dependencias de AWS SDK (solo tipos)

CLI Integration

  • jamx build: Compila el adaptador
  • jamx deploy lambda: Despliega a AWS Lambda (con SAM/Serverless Framework)

This adapter provides seamless integration between JAMX Framework and AWS Lambda, enabling developers to build serverless applications with type safety and minimal configuration while leveraging the full power of JAMX's handler model.