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

@cbm-common/data-access

v0.0.7

Published

Esta librería proporciona clases reutilizables para manejar operaciones de listado y paginación en forma reactiva: `ListService` y `PaginatedListService`.

Downloads

766

Readme

data-access — Biblioteca de acceso a datos (List y PaginatedList)

Esta librería proporciona clases reutilizables para manejar operaciones de listado y paginación en forma reactiva: ListService y PaginatedListService.

Resumen de artefactos

  • ListService<T, R>: clase base que realiza la llamada al repositorio, transforma la respuesta (mapFn) y expone señales (data, loading) y helpers (list(), getParams(), setParams(), updateParams()).
  • PaginatedListService<T, R>: extiende ListService añadiendo soporte de paginación (señal pagination, métodos nextPage, getters/setters de paginado y list(resetPg?: boolean)).
  • Modelos expuestos:
    • ListModel.Repository<T>: contrato que debe exponer destroyRef y list$ (función que devuelve Observable).
    • ListModel.Config<T,R>: opciones: mapFn, notificationService, typeahead.
    • PaginatedListModel.Paginated: forma { page, size, pages, records } y valor inicial initPaginated.

Concepto y comportamiento

  • Ambas clases no son Angular services (no llevan @Injectable) sino helpers/clases que se instancian desde otros servicios o componentes con una dependencia repository (implementación concreta que expone list$ y destroyRef).
  • ListService maneja:
    • data (señal con el resultado transformado por mapFn).
    • loading (señal booleana durante la petición).
    • typeahead (si config.typeahead está definido, typeahead$ se escucha y actualiza params tras debounce).
    • notificationService (si se pasa en config, se usa para mostrar errores).
  • PaginatedListService agrega paginación y funciones para avanzar páginas, preservar parámetros y mapear la respuesta con acceso a la señal de paginado.

Tipos clave (resumen)

  • ListModel.Repository:

    • destroyRef: DestroyRef (para takeUntilDestroyed)
    • list$: (...args: any[]) => Observable
  • ListModel.Config<T,R>:

    • mapFn?: (res: T, pg?: WritableSignal<PaginatedListModel.Paginated>) => R
    • notificationService?: servicio con método sendAlert (opcional)
    • typeahead?: string — nombre del parámetro que se usará para búsquedas tipo typeahead

Ejemplo básico de uso

Supongamos que tienes un repositorio con la forma esperada:

// repo.mock.ts (ejemplo)
const repo = {
   destroyRef: someDestroyRef,
   list$: (params: any) => httpClient.get('/api/items', { params })
};

// crear servicio de lista
const listService = new ListService(repo, {
   mapFn: (res) => res.items, // transformar respuesta
   notificationService: notificationServiceInstance,
   typeahead: 'q'
});

// usar
await listService.list();
console.log(listService.data());

Ejemplo con paginación:

const paginated = new PaginatedListService(repo, { mapFn: (res, pg) => res.items });
await paginated.list();
paginated.nextPage(searchTerm);

Notas de implementación

  • ListService usa takeUntilDestroyed(this._destroyRef) para cancelar observables cuando el consumer se destruye; por ello repository.destroyRef debe estar presente.
  • mapFn permite adaptar la respuesta del backend al tipo consumido por la UI. Si no se provee, se usa defaultMapFn que hace un cast simple.

Errores comunes y sugerencias

  • "La propiedad se usa antes de su inicialización" (TypeScript/ESNext class fields):

    • Si ves un error tipo La propiedad "_config" se usa antes de su inicialización es probable que la configuración del compilador (useDefineForClassFields) o la forma en que se declaran propiedades haga que las inicializaciones de campos que dependen de parámetros del constructor intenten evaluarse antes del constructor.
    • Solución práctica: mover cualquier inicialización que use this._config o this._repository a dentro del constructor o definir las propiedades sin inicializar y asignarlas en el constructor. De esta forma se evita acceder a campos antes de tiempo.
  • Ejemplo de corrección (esquema):

// incorrecto (campo inicializado con referencia a parámetro del constructor)
protected readonly notificationService = this._config.notificationService; // puede fallar

// correcto (asignar en constructor)
protected readonly notificationService: any;
constructor(repo, config) {
   this.notificationService = config.notificationService;
}

Pruebas y validación

  • Para probar las clases crea mocks del repository que expongan list$ (por ejemplo of(mockResponse)) y un destroyRef apropiado. Testea list(), comportamiento de loading, y que mapFn transforma el resultado.

Contribuciones y extensión

  • Puedes extender ListService para soportar caching, cancelación explícita de peticiones o estrategia de reintento.

Si quieres, implemento:

  • ejemplos de tests unitarios (Jest/Karma) para ListService y PaginatedListService;
  • o aplico la corrección automática para evitar el problema de inicialización de propiedades (mover inicializaciones al constructor). Indica cuál prefieres.