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

smartport-lib

v1.4.3

Published

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

Downloads

346

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'],
  token: 'mi-token', // Opcional. Token para Basic Auth en peticiones al API
  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é local (o fuerza lectura desde archivo/API si no está cargado).

options:

  • ev: string — evento a consultar
  • filter: object — filtros MongoDB-like ($in, $gt, $lt, $regex, $ne, $nin, $or)
  • 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
const persons = await cache.getData('person', {
  ev: 'nac',
  limit: 10,
  skip: 0,
  sort: 'nombre:asc',
  filter: { tipo: { $ne: 'admin' } },
  search: 'alberto'
});

getAPI(endpoint, options)

Consulta datos directamente desde el API, sin pasar por el caché local. Acepta la misma firma que getData.

options:

  • ev: string — evento a consultar
  • filter: object — filtros (se envían como query params al API)
  • sort: string — campo y orden (se traduce a sort + order para el API)
  • limit: number — cantidad máxima de resultados
  • skip: number — resultados a omitir
  • search: string — búsqueda libre
  • token: string — token para Basic Auth (opcional, usa el del constructor si no se pasa)
const persons = await cache.getAPI('person', {
  ev: 'nac',
  limit: 10,
  skip: 0,
  sort: 'nombre:asc',
  filter: { tipo: { $ne: 'admin' } },
  search: 'alberto',
  token: 'mi-token' // opcional
});

postAPI(endpoint, body, options)

Envía una petición POST al API con Basic Auth.

  • Sin archivos: envía como application/x-www-form-urlencoded (compatible con $_POST)
  • Con archivos: envía como multipart/form-data (compatible con $_FILES + $_POST)

Parámetros:

  • endpoint: string — ruta del endpoint
  • body: object — datos a enviar como campos POST
  • options: object — { ev, token, files } opcionales
  • options.files: object — mapa de { nombre: ruta } o { nombre: [ruta1, ruta2] } para múltiples archivos
// Sin archivos — cada campo llega como $_POST['titulo'], $_POST['tipo'], etc.
const nuevo = await cache.postAPI('banners/create', {
  titulo: 'Mi Banner',
  tipo: 'principal',
  date: '2026-04-02'
}, { ev: 'nac', token: 'mi-token' });

// Con un archivo — llega como $_FILES['picture'] en PHP
const conFoto = await cache.postAPI('banners/create', {
  titulo: 'Mi Banner'
}, {
  ev: 'nac',
  files: { picture: 'C:/ruta/a/imagen.jpg' }
});

// Con múltiples archivos en un campo
const galeria = await cache.postAPI('banners/create', {
  titulo: 'Galería'
}, {
  ev: 'nac',
  files: { newpicture: ['C:/ruta/foto1.jpg', 'C:/ruta/foto2.jpg'] }
});

💡 Tip: Si recibes archivos desde un formulario HTML en Express, usa multer para guardarlos temporalmente y pasa las rutas a files:

const multer = require('multer');
const upload = multer({ dest: 'uploads/' });

app.post('/crear-banner', upload.single('picture'), async (req, res) => {
  const result = await cache.postAPI('banners/create', req.body, {
    ev: 'nac',
    files: { picture: req.file.path }
  });
  res.json(result);
});

getCount(endpoint, options)

Devuelve la cantidad de documentos en caché que coinciden con los filtros.

options:

  • ev: string — evento a consultar
  • filter: object — filtros MongoDB-like
  • search: string — búsqueda libre
const total = await cache.getCount('person', {
  ev: 'nac',
  filter: { tipo: 'jugador' },
  search: 'alberto'
});

updateDocument(endpoint, id, updateObj, params)

Actualiza un solo documento (por _id) dentro del JSON cacheado y lo persiste en disco. No llama al API.

  • endpoint: string — endpoint del caché
  • id: string — el _id (o $oid) del documento
  • updateObj: object — campos a actualizar (merge superficial)
  • params: object — { ev } opcional
const result = await cache.updateDocument('person', '663a1b...', { nombre: 'Nuevo Nombre' }, { ev: 'nac' });
// result: { success: true, item: { ... } }

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. Todas las rutas soportan segmentos anidados (/:alias, /:alias/:extra, /:alias/:extra/:id).

Rutas de datos:

GET /data/:alias

Rutas de actualización de caché (requieren smartport-key):

GET /update/:alias
GET /update-multiple?endpoint[]=a&endpoint[]=b

Rutas de eliminación de caché (requieren smartport-key):

GET /delete/:alias
GET /delete-multiple?endpoint[]=a&endpoint[]=b

Actualización de un solo documento por ID (requiere smartport-key):

POST /updatev2/:alias/:id

Recibe el payload en el body (JSON) o como query param update/data/payload.


📦 Variables de entorno compatibles

Puedes usar .env para centralizar configuración:

SmartPort-ApiURL=https://api.smartportgms.com
SmartPort-ev=nac
SmartPort-Key=123456
SmartPort-Token=mi-token-secreto

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

Las rutas /update, /update-multiple, /updatev2, /delete y /delete-multiple 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(express.json()); // necesario para POST /updatev2
app.use('/SmartPort', cache.getRouter());

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

📚 Filtros compatibles (filter)

Las funciones getData() y getCount() soportan 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' } }
  • $or: Coincide si alguna de las condiciones se cumple.

    { $or: [{ tipo: 'jugador' }, { tipo: 'coach' }] }
  • 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