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

@coppel/mslite

v1.0.3

Published

Framework para el desarrollo de microservicios

Downloads

28

Readme

Micro servicios

El micro servicio hereda de Worker o Fork dependiendo del elemento que se quiera crear.

NOTAS.

Las posibles acciones que tienen un micro servicio son:

  • List
  • Create
  • Get
  • Update
  • Delete

Esta son definidas utilizando decoradores tal como se muestra en el ejemplo.

Ejemplo:

import { ErrorMs, Microservice, MsManager } from '@coppel/mslite';

@MsManager.define({
    App: 'NombreApp',
    Name: 'NombreWorker',
    Version: 'v1',
    Broker: ['127.0.0.1:9092'],
    Debug: true
})
class MiWorker extends Microservice {

    /**
     * Metodo de smoketest
     */
    public smoketest(): boolean | Promise<boolean> {
        // Retornar la promesa
        return new Promise( ( rr: (r: boolean) => void, ff: (r: boolean) => void ) => {
            rr(true);
        });
    }

    /**
     *  Errores que puede tener el servicio.
     */
    @MsManager.Errors()
    public errores(): ErrorMs {
        return {
            '-12': 'Error definido por el usuario',
        };
    }

    // Para recuperar cierta informacion se utilizan los siguientes parametros, y colocas nada mas lo que requieras
    // @MsManager.ctx('data') data: any
    // @MsManager.ctx('uuid') id: any
    // @MsManager.ctx('authorization') auth: any
    // @MsManager.ctx('response') resp: any

    @MsManager.List()
    public metodoList(@MsManager.ctx('uuid') id: any, @MsManager.ctx('authorization') auth: any): any {
        // Listar
    }

    @MsManager.Create()
    public crear(@MsManager.ctx('data') data: any, @MsManager.ctx('authorization') auth: any): any {
        // Registrar
    }

    @MsManager.Get()
    public recuperar(@MsManager.ctx('uuid') id: any, @MsManager.ctx('authorization') auth: any): any {
        // Recuperar un elemento
    }

    @MsManager.Update()
    public actualizar(@MsManager.ctx('data') data: any, @MsManager.ctx('uuid') id: any, @MsManager.ctx('authorization') auth: any): any {
        // Actualizar un elemento
    }

    @MsManager.Delete(@MsManager.ctx('uuid') id: any, @MsManager.ctx('authorization') auth: any)
    public eliminar(data: any, auth: boolean, id: any): any {
        // Eliminar un elemento
    }

}

NOTAS:

Las clases son auto ejecutables, no se requiere que se implemente una inicializacio/start o similar para poner en marcha el servicio.

Diseño Legado.

Si lo que se quiere es crear un micro servicio basado en el diseño de la version v1.* se utiliza la definicion de *Listener*, como se indica en el siguiente ejemplo:

import { ErrorMs, Microservice, MsManager } from "@coppel/mslite";

@Ms.define({
    App: "NombreApp",
    Name: "NombreWorker",
    Version: "v1",
    Broker: ["127.0.0.1:9092"],
    Debug: true
})
class MiWorker extends Microservice {
    /**
     * Metodo de smoketest
     */
    public smoketest(): boolean | Promise<boolean> {
        // Retornar la promesa
        return new Promise((rr: (r: boolean) => void, ff: (r: boolean) => void) => {
            rr(true);
        });
    }

    /**
     *  Errores que puede tener el servicio.
     */
    @MsManager.Errors()
    public errores(): ErrorMs {
        return {
            "-12": "Error definido por el usuario"
        };
    }

    @MsManager.Listener()
    public metodoList(@MsManager.ctx("data") data: any, @MsManager.ctx("authorization") auth: any): any {
        // Escuchar todos los eventos
    }
}

Retorno de valores

Para retornar una respuesta simplemente se debe regresar el valor de la funcion:

  @MsManager.Get()
  public miFuncion(@MsManager.ctx('data') data: any, @MsManager.ctx('authorization') auth: any): object {
       // Retorno de un objeto
       return {
           Clave: 'Valor',
       };
   }

NOTAS:

En caso de que se requiera regresar un valor con una promesa:

  @MsManager.Get()
  public miFuncion(@MsManager.ctx('data') data: any, @MsManager.ctx('authorization') auth: any): Promise<object> {
      // Retornar la promesa
      return new Promise( (resolve: any, fail: any) => {
          resolve({ Clave: 'Valor' });
      });
  }

El core detecta la promesa, y espera que se resuelva para retornar la respuesta a la peticion inicial.

Errores

Para la notificacion de errores, se implementa la utilizada por el lenguaje, llamando a la propiedad heredada Errors, como muestra el ejemplo.

  @MsManager.Get()
  public miFuncion(@MsManager.ctx('data') data: any, @MsManager.ctx('authorization') auth: any): object {
       // Ejecutar el error.
       throw this.emitError('-34'); // definido antes.
   }

Esto ejecutara la excepcion que es escuchada, por el core, notificando a la peticion original.

NOTAS:

Cuando se utiliza una promesa se puede implementar el llamdo a la excepcion como el ejemplo anterior o de la siguiente manera.

  @MS.Get()
  public miFuncion(@MsManager.ctx('data') data: any, @MsManager.ctx('authorization') auth: any): Promise<object> {
      // Retornar la promesa
      return new Promise( (resolve: any, fail: any) => {
          fail(this.emitError('-34'));
      });
  }

Ambas opciones generar un error que es enviado por el core.

Bifurcaciones

import { Actions, ConfForks, ErrorMs, Microservice, MsManager } from "@coppel/mslite";

@MsManager.define({
    App: "NombreApp",
    Name: "NombreWorker",
    Version: "v1",
    Broker: ["127.0.0.1:9092"],
    Debug: true
})
class MiWorker extends Microservice {
    /**
     * Metodo de smoketest
     */
    public smoketest(): boolean | Promise<boolean> {
        // Retornar la promesa
        return new Promise((rr: (r: boolean) => void, ff: (r: boolean) => void) => {
            rr(true);
        });
    }

    /**
     *  Errores que puede tener el servicio.
     */
    @MsManager.Errors()
    public errores(): ErrorMs {
        return {
            "-12": "Error definido por el usuario"
        };
    }

    @MsManager.Fork()
    public configFork(): ConfForks {
        return {
            bif: {
                App: "appcoppel",
                Name: "prueba2",
                Version: "v1"
            },
            demo: {
                App: "appcoppel",
                Name: "simple",
                Version: "v1"
            }
        };
    }

    public initData(req: any, resp: any): any {
        return 10;
    }

    @MsManager.Listener([
        { action: Actions.DEFAULT, fork: "bif" },
        { action: Actions.CREATE, fork: "demo", fnc: "initData" } // Sin datos, se para data tal como llega
    ])
    public metodoList(@MsManager.ctx("request") data: any): any {
        return { todo: "ok1" };
    }
}