DEV Community

Cover image for Un opérateur RXJS pour debugger avec élégance ?
Timothy Alcaide
Timothy Alcaide

Posted on

Un opérateur RXJS pour debugger avec élégance ?

Tous les développeurs utilisant RXJS qui ont voulu déboguer ont déjà fait :

obs$.pipe(tap((v) => console.log("data", v)))
// ou pour les plus malins.
obs$.pipe(tap(console.log)) 
Enter fullscreen mode Exit fullscreen mode

C'est pas très fun. Pour y remédier, on va créer un opérateur personnalisé qui nous permettra d'avoir :

rxjs operateur debug output

Plus sympa comme logs non ?
Pour l'utiliser, il suffit de le passer dans le pipe :

import { debug } from './custom.operators.ts'

obs$.pipe(debug("data"));
Enter fullscreen mode Exit fullscreen mode

Côté implémentation, c’est simple :

export function debug<T>(tag = 'Untitled') {
  if (environment.production) {
    return tap<T>();
  }

  const t = tag[0].toUpperCase() + tag.slice(1);

  return tap<T>({
    next(value: T) {
      console.log(
        `%c[${t}: Next]`,
        'background: #84cc16; color: #fff; padding: 3px; font-size: 9px; font-weight: 500;',
        value
      );
    },
    error(error) {
      console.log(
        `%[${t}: Error]`,
        'background: #ef4444; color: #fff; padding: 3px; font-size: 9px; font-weight: 500;',
        error
      );
    },
    complete() {
      console.log(
        `%c[${t}]: Complete`,
        'background: #6b7280; color: #fff; padding: 3px; font-size: 9px; font-weight: 500;'
      );
    },
  });
}
Enter fullscreen mode Exit fullscreen mode

En bonus, j'ai ajouté une petite ligne en haut pour ne pas logger en production.

Voilà :) Happy coding !

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more