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

yoonite-saga

v1.2.22

Published

> Sing a song and run saga !

Downloads

185

Readme

Yoonite Saga

Sing a song and run saga !

Inspiré de https://www.npmjs.com/package/node-sagas, nous avions besoin d'un moteur de workflow un peu plus complet et avons créer notre propre library. Elle permet d'écrire et d'exécuter des workflows de type "saga" de manière orchestrée. Pratique dans des architectures distribuées ou simplement dans des enchainements d'étapes au sein du code.

Install

npm i yoonite-saga

Usage

L'objectif est de constituer une suite d'étapes à exécuter (ou pas) avec une syntaxe simple :

import { SagaBuilder, SagaProcessor } from "yoonite-saga";

const builder = new SagaBuilder({ debug: true });

const myCustomWorkflow = builder
  .step("My first step")
  .invoke(() => console.log("Let's go !"));

  .step("My second step")
  .invoke(() => console.log("again !"));

// ...

const processor = new SagaProcessor<T>();
processor.add(myCustomWorkflow);
const response = await processor.start();

Functions

A chaque étape, on peut ajouter ou modifier des informations dans le context d'exécution et s'en servir dans les étapes suivantes :

const myCustomWorkflow = builder
  .step("Create initial context")
  // Inject some informations you need into context
  .invoke(() => ({ accountId: "123" }))

  .step("Use context")
  // Get information from current context
  .invoke(({ accountId }) => {
    console.log(`Let's go with account ${accountId} !`);
  });

On peut utiliser les async/await pour gérer l'asynchrone et remplir son context pour plus tard :

  .step("Get account's informations")
  // Use asynchrone stuff...
  .invoke(async ({ accountId }) => {
    // Async request
    const account = await request.get(`/accounts/${accountId}`);

    // Populate current context with new informations
    return { account };
  })

On peut stacker les invoke d'une step pour séparer son code et améliorer la lisibilité :

  .step("Get account's pets")
  // Use many invokes for a step...
  .invoke("Get cats", async ({ accountId }) => {
    const cats = await request.get(`/cats/${accountId}`);
    return { cats };
  })
  .invoke("Get dogs", async ({ accountId }) => {
    const dogs = await request.get(`/dogs/${accountId}`);
    return { dogs };
  });

On peut utiliser des conditions pour éviter une step :

  .step("Get a dog vaccines")
  // Use context (or not) into a condition to skip unwanted step...
  .condition(({ dogs }) => dogs.length > 0) // true or false
  .invoke("Get vaccines", async ({ dogs }) => {
    const { dogId } = dogs[0]
    const vaccines = await request.get(`/vaccines/${dogId}`);
    return { vaccines };
  })

Si on a plusieurs invoke, ça saute toute la step :

  .step("Get a dog vaccines")
  .condition(({ alwaysFalse }) => alwaysFalse)
  .invoke("Not executed", async ({ dogs }) => {
    const { dogId } = dogs[0]
    const vaccines = await request.get(`/vaccines/${dogId}`);
    return { vaccines };
  })
  .invoke("Not executed either", ({ vaccines }) => {
    console.log("Les vaccins du chien:", vaccines)
  })

On peut placer des conditions sur chacun des invoke :

  .step("Get account's pets")
  // Use many invokes for a step...
  .invoke("Get cats", {
    condition: ({ alwaysFalse }) => alwaysFalse,
    action: async ({ accountId }) => {
      const cats = await request.get(`/cats/${accountId}`);
      return { cats };
    }
  })
  .invoke("Get dogs", {
    condition: ({ alwaysTrue }) => alwaysTrue,
    action: async ({ accountId }) => {
      const dogs = await request.get(`/dogs/${accountId}`);
      return { dogs };
    }
  })

Dans le cas ou une exception est levée, le système la capture et arrête l'exécution. Les steps d'après ne seront pas exécutées :

  .step("Something is going to happen")
  .invoke(() => {
    throw new Error("S.O.S")
  })

  .step("Not executed")
  .invoke(() => {
    // ...
  })

Si on veut exécuter du code quand une exception est levée, on compense ! Seules les compensations des étapes dans lesquelles ont est passées peuvent s'exécuter...

.step("Usual stuff")
  .invoke(() => {
    const orderId = await request.put(`/orders`, { amount: 666 });
    return { orderId };
  })
  .withCompensation(({ orderId }) => {
    // Cancel order
    await request.delete(`/orders`, { orderId });
  })

  .step("Something is going to happen")
  .invoke(() => {
    throw new Error("Error in shipping")
  })

  .step("Not executed")
  .invoke(() => {
    // ...
  })

Les compensations peuvent se définir pour chaque invoke également :

.step("Usual stuff")
  .invoke({
    action: () => {
      const orderId = await request.put(`/orders`, { amount: 666 });
      return { orderId };
    },
    withCompensation: ({ orderId }) => {
      // Cancel order
      await request.delete(`/orders`, { orderId });
    }
  })

Response

Lorsque le processor retourne le résultat de l'exécution d'un workflow, voici les informations obtenues :

{
  state: "success" | "failed";
  context: { ... }; // Le context final
  history: any[]; // Le détails de l'exécution
  errors: Array<Exception>; // Si il y en a eu
}

Services

Il arrive souvent que les workflows utilisent tous une même fonctionnalité (une classe, un module, un service externe, etc...). Pour éviter des copiés / collés inutiles, il est possible d'enregistrer des services dans le processor pour les utiliser ensuite :

import { myCustomLogService } from "myCustomLogService";

const processor = new SagaProcessor<T>({
  myCustomLogService,
});

On peut ensuite l'utiliser dans les workflows :

.step('Use my custom service')
.invoke((
    { contextVar1, contextVar2, ...otherContextVars },
    { myCustomLogService }, // Second parameter
  ) => {
    // Do stuff...

    myCustomLogService.log(contextVar1)
  })