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 🙏

© 2024 – Pkg Stats / Ryan Hefner

cm-idempotencia

v1.4.6

Published

Libreria para el manejo de la idempotencia

Downloads

376

Readme

cm-idempotencia

Librería para implementar fácilmente el modelo de idempotencia en una api hecha en fastify.

Instalación

yarn add cm-idempotencia

Implementación

Importar el método handler de cm-idempotencia y definir los valores asi:

import { handler } from 'cm-idempotencia';

const exampleRouteHandler = handler({
    serviceName: 'cm-service-example-name',
    keyId: 'process_id',
    isPubsub: true,
});

Implementación de las dependencias de la librería

Buscar la función en nuestro código donde se tenga implementado el servidor (Express, Fastify, etc). Y llamar la función dependenciasIdempotencia(), se puede llamar en cualquier parte de la ejecución del flujo de la aplicación, la idea principal es que se ejecute siempre que inicia nuestro servidor.

Ejemplo Fastify

import { application } from './Application';
import { createDependencyContainer } from '@configuration';
import { dependenciasIdempotencia } from 'cm-idempotencia'; //Importar la funcion desde la libreria
import { ENV } from '@util';

const start = async () => {
    // Iniciar el servidor
    const port = ENV.PORT;
    try {
        const server = await application.listen(port, '0.0.0.0');
        createDependencyContainer();
        dependenciasIdempotencia(); //Llamar la funcion mencionada despues de iniciar el servidor
        console.log(`Application running on ${server}`);
    } catch (error) {
        console.error(error);
        await application.close();
    }
};
start();

Campos

  • serviceName: Nombre del servicio, esto sera usado como nombre de la colección dentro de la instancia de redis. Se puede pasar cualquier nombre pero se recomienda que sea el nombre del servicio para envitar conflictos en caso de que la instancia de redis sea compartida.
  • keyId: El nombre de la propiedad que contiene el identificador de la petición, el nombre que se le pase tiene que existir en el body de la petición. Siguiendo este ejemplo, en el body tiene que existir un campo process_id que contiene el un identificador único de la petición, de lo contrario habrá un error. Si nuestro identificar se encuentro en un subObjeto, se puede pasar el nombre del campo con un punto, ejemplo: subObjeto.process_id.
  • isPubsub: En caso que sea por un topic de PubSub.

Después cuando se defina la ruta se utiliza el handler de esta manera:

application.post(`/example-route`, exampleRouteHandler, exampleRoute);

NOTA:

Se debe tener una instancia de redis lista para que la libreria pueda funcionar. Definir como variables de entorno los siguientes valores: REDIS_HOST y REDIS_PORT

REDIS_CONNECTION_LOCAL_ENV

Esta es una variable de entorno que debe ser definida, su valor es boleano y será true cuando el redis a utilizar este definido localmente, ósea dentro del mismo contenedor de docker de la aplicación (docker compose). A continuación un ejemplo:

Archivo docker-compose.yml

version: '3.7'
services:
    redis:
        image: redis:7.0.4
        restart: always
        command: redis-server --bind 0.0.0.0

En este caso el redis esta definido en el docker-compose, en el mismo archivo estará definido el contenedor de nuestra aplicación. REDIS_CONNECTION_LOCAL_ENV tendrá un valor de true y hará referencia al contenedor de redis llamado redis la conexión será automática.

Si el redis es externo y necesitamos el REDIS_HOST y REDIS_PORT entonces REDIS_CONNECTION_LOCAL_ENV tendrá un valor de false

NOTAS DE LA VERSION

  • 1.4.5
    • Esta version utiliza la version 3.28 de fastify, si se requiere una version mas actual, utilizar la version de cm-idempotencia 1.4.4 o anteriores.