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 🙏

© 2025 – Pkg Stats / Ryan Hefner

smartport-lib

v1.2.0

Published

Librería de caché inteligente y gestión de endpoints API para SmartPort

Readme

SmartPort-Lib

SmartPort-Lib es una librería de Node.js para gestionar y servir datos cacheados desde endpoints externos (APIs) de forma eficiente, diseñada específicamente para el sistema deportivo SmartPort. Esta herramienta permite manejar datos temporales con soporte para filtros, ordenamientos, búsquedas, paginación y almacenamiento local en disco.


🚀 Instalación

npm install smartport-lib

🔧 Uso básico

const SmartPort = require('smartport-lib');

const cache = new SmartPort({
  ev: 'nac', // Evento por defecto
  apiUrl: 'https://api.smartportgms.com',
  endpoints: ['events', 'juegos', 'person', 'users', 'tourney']
});

📁 Estructura de parámetros

new SmartPort({
  ev: 'nac', // Opcional. Evento por defecto (también puede venir de process.env)
  apiUrl: 'https://tu.api.url',
  endpoints: ['events', 'juegos', 'person'],
  cacheDir: './cache', // Carpeta donde se guardan los archivos JSON cacheados
  cacheDuration: 600000 // Duración del caché en milisegundos
});

🧩 Métodos principales

getData(endpoint, options)

Obtiene datos desde el caché (o fuerza lectura desde archivo si no está cargado).

options:

  • ev: string — evento a consultar
  • filter: object — filtros MongoDB-like ($in, $gt, $lt, $regex, etc.)
  • sort: string — campo y orden (nombre:asc, fecha:desc, random)
  • limit: number — cantidad máxima de resultados
  • skip: number — resultados a omitir
  • search: string — búsqueda libre por todos los campos

updateCache(endpoint, params)

Fuerza actualización del caché desde la API.

refresh(endpoint, params)

Alias de updateCache.

getRouter()

Devuelve un express.Router() con endpoints listos para usar:

/SmartPort/data/:alias
/SmartPort/update/:alias
/SmartPort/delete/:alias
/SmartPort/update-multiple?endpoint[]=a&endpoint[]=b
/SmartPort/delete-multiple?endpoint[]=a&endpoint[]=b

📦 Variables de entorno compatibles

Puedes usar .env para centralizar configuración:

SmartPort-ApiURL=https://api.smartportgms.com
SmartPort-ev=nac
SmartPort-Key=123456

🛡️ Seguridad (actualización/eliminación)

Las rutas /update y /delete exigen ?smartport-key=... y se validan contra process.env['SmartPort-Key'].


🧪 Ejemplo en Express

const express = require('express');
const SmartPort = require('smartport-lib');

const app = express();
const cache = new SmartPort({
  endpoints: ['events', 'juegos']
});

app.use('/SmartPort', cache.getRouter());

app.listen(3000, () => {
  console.log('Servidor SmartPort corriendo en http://localhost:3000');
});

📚 Filtros compatibles (filter)

La función getData() soporta filtros tipo MongoDB para arrays y objetos simples. Los disponibles son:

  • $in: Coincide si el valor está incluido en el array.

    { alias: { $in: ['TRU', 'SUC'] } }
  • $nin: Coincide si el valor no está en el array.

    { picture: { $nin: ['url1', 'url2'] } }
  • $gt / $lt: Comparaciones numéricas o por fecha.

    { edad: { $gt: 18 } }
    { date: { $lt: '2025-01-01' } }
  • $ne: Coincide si el valor es diferente.

    { tipo: { $ne: 'admin' } }
  • $regex: Coincidencia parcial insensible a mayúsculas.

    { nombre: { $regex: 'alberto' } }
  • Fechas MongoDB ($date): Comparadas automáticamente con formato YYYY-MM-DD o DD/MM/YYYY.

    { fechaNacimiento: { $lt: '01/01/2025' } }

🧠 También se detectan y comparan automáticamente campos tipo ObjectId ($oid) y fechas con estructura Mongo ($date).


👤 Autor

Alberto Toro
GitHub: @toroalbert


🪪 Licencia

MIT