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

@ponchoceniceros/sap

v0.0.1

Published

Módulo TypeScript para conectar con SAP Service Layer y HANA Database

Readme

SAP Module

Módulo TypeScript para conectar con SAP Service Layer y HANA Database.

Instalación

npm install @ponchoceniceros/sap

Uso básico

import { SapConn, SapApi, SessionHandler } from '@ponchoceniceros/sap';
import type { SapCredentials, SapAPI, SapSessionHandler } from '@ponchoceniceros/sap';

// Configurar credenciales
const credentials = SapConn();

// Crear handler de sesión
const sessionHandler = SessionHandler(credentials);

// Crear API client
const sapApi = SapApi();

// Login
await sessionHandler.login();

// Ejemplo de uso con Service Layer
const wrappedGet = sessionHandler.onSession(sapApi.get);
const result = await wrappedGet('BusinessPartners', '$top=10');

// Ejemplo de uso con HANA
const wrappedHanaGet = sessionHandler.hana.onSession(sapApi.hana.get);
const hanaResult = await wrappedHanaGet('SELECT * FROM "MY_TABLE" LIMIT 10');

Patrones de uso en aplicación real

1. Provider Pattern (Recomendado)

Basado en src/orders/providers.ts:

import { SapConn, SapApi, SessionHandler } from '@ponchoceniceros/sap';
import type { SapCredentials, SapAPI, SapSessionHandler } from '@ponchoceniceros/sap';

/**
 * Proveedor centralizado de servicios SAP
 */
function SapProvider() {
  const credentials: SapCredentials = SapConn();
  const hdl: SapSessionHandler = SessionHandler(credentials);
  const api: SapAPI = SapApi();

  return { hdl, api };
}

// Uso en la aplicación
const { hdl, api } = SapProvider();

2. Service Layer Queries

Basado en src/application/orders.ts:

import type { SapAPI, SapSessionHandler } from '@ponchoceniceros/sap';

/**
 * Consulta de órdenes desde Service Layer
 */
async function getOrdersBySl(hdl: SapSessionHandler, api: SapAPI) {
  // Documento específico
  const query = `Orders(2832)`;
  
  // Lista con filtros
  // const query = `Orders?$filter=DocNum eq 986&$select=DocNum,DocEntry,DocumentLines`;
  
  // Lista simple
  // const query = `Orders?$select=DocNum,DocEntry`;

  const resp = await hdl.onSession(api.get)(query, 10);
  return resp;
}

3. HANA Database Queries

/**
 * Consulta de órdenes desde HANA Database
 */
async function getOrdersByHana(hdl: SapSessionHandler, api: SAP) {
  const company = hdl.hana.getCompany();
  const query = `select v."DocEntry" from ${company}.ORDR v limit 1`;

  const resp = await hdl.hana.onSession(api.hana.get)(query);
  return resp;
}

4. Inicialización de la aplicación

Basado en src/server.ts:

import "dotenv/config";
import { SapConn, SessionHandler } from '@ponchoceniceros/sap';

// Inicialización al iniciar el servidor
async function initializeApp() {
  const credentials = SapConn();
  const hdl = SessionHandler(credentials);
  await hdl.login();
  
  console.log('SAP Service Layer inicializado');
  return hdl;
}

5. Imports de tipos optimizados

// Importar solo tipos (mejor control)
import type { SapAPI, SapSessionHandler, ApiResponse } from '@ponchoceniceros/sap';

// Importar implementaciones
import { SapConn, SapApi, SessionHandler } from '@ponchoceniceros/sap';

// Funciones tipadas
function processResponse(response: ApiResponse<unknown>) {
  // ...
}

Variables de entorno

# Service Layer
SAP_API_SL_URL=https://your-sap-server:50000/b1s/v1
SAP_API_COMPANY=YOUR_COMPANY_DB
SAP_API_SL_UID=your_username
SAP_API_SL_PWD=your_password
SAP_API_SL_STG=redis://localhost:6379

# HANA Database
SAP_API_HN_URL=hanadb:30015
SAP_API_HN_UID=your_hana_user
SAP_API_HN_PWD=your_hana_password
SAP_API_HN_SSL=false

# Debug mode (opcional)
SAP_DEBUG=true

Modo Debug

Habilitar debug por variable de entorno

export SAP_DEBUG=true

Habilitar debug en código

// Opción 1: Por variable de entorno
const sessionHandler = SessionHandler(credentials);

// Opción 2: Parámetro explícito
const sessionHandler = SessionHandler(credentials, { debug: true });

// Opción 3: Combinación de colores y debug
const sessionHandler = SessionHandler(credentials, { 
  debug: true,
  colors: {
    RED: '\x1b[91m',  // Rojo brillante
    GREEN: '\x1b[92m', // Verde brillante
    BLUE: '\x1b[94m',  // Azul brillante
    CIAN: '\x1b[96m'   // Cian brillante
  }
});

Comportamiento del modo debug

El modo debug se activa automáticamente si:

  • SAP_DEBUG=true (variable de entorno)

  • NODE_ENV=development (desarrollo)

  • options.debug = true (parámetro explícito)

  • Debug activado: Muestra logs de conexión, reintentos, sesiones, etc.

  • Debug desactivado: Oculta todos los logs internos (silencioso)

Logs disponibles:

  • [🔧] Debug mode: ON (estado del modo debug)
  • [🔧] SAP_DEBUG: {valor} (valor de variable)
  • [🔧] NODE_ENV: {valor} (entorno actual)
  • [📁] sesion previa existente: {sessionId}
  • [📁] nueva sesion cargada: {sessionId}
  • [📁] primer intento de uso de la sesion...
  • [📁] la sesión falló, segundo intento...
  • [📁] inyeccion de los parametros de conexion a la db...

API Reference

Functions

  • SapConn(): Obtiene credenciales desde variables de entorno
  • SapApi(): Crea cliente para SAP Service Layer y HANA
  • `SessionHandler(credentials, options?): Maneja sesiones con auto-reconnect

Opciones de SessionHandler:

interface SessionHandlerOptions {
  colors?: {    // Colores personalizados para logs
    RED?: string;
    GREEN?: string;
    BLUE?: string;
    CIAN?: string;
  };
  debug?: boolean;  // Mostrar/ocultar logs de debug (default: process.env.SAP_DEBUG)
}

Types

  • SapCredentials: Interfaz de credenciales SAP
  • SapAPI: Interfaz del cliente API
  • SapSessionHandler: Interfaz del handler de sesión
  • ApiResponse<T>: Respuesta genérica de API
  • SapSession: Información de sesión activa

Métodos principales

Service Layer

hdl.onSession(api.get)(endpoint: string, maxPageSize?: number)

HANA Database

hdl.hana.onSession(api.hana.get)(query: string)
hdl.hana.getCompany() // Returns company database

Características

  • ✅ Auto-reconnect de sesiones
  • ✅ Tipado completo con TypeScript
  • ✅ Soporte para Service Layer y HANA
  • ✅ Manejo de errores centralizado
  • ✅ Session storage con Redis
  • ✅ Imports optimizados de tipos

Licencia

MIT