Skip to content

Repository files navigation

@mindfullabai/webhook-notifications

Un client TypeScript/JavaScript per l'invio di notifiche webhook con supporto dual-build per TypeScript e JavaScript puro.

npm version TypeScript License: MIT

🚀 Caratteristiche

  • Dual Build: Supporto nativo per TypeScript e JavaScript
  • Type Safety: Tipizzazione completa per sviluppatori TypeScript
  • IntelliSense: Autocompletamento avanzato anche in JavaScript
  • Retry Logic: Gestione automatica dei retry con backoff
  • Runtime Detection: Supporto per Node.js e browser
  • Validation: Validazione degli input integrata
  • Zero Dependencies: Usa solo node-fetch per Node.js < 18

📦 Installazione

# NPM
npm install @mindfullabai/webhook-notifications

# Yarn
yarn add @mindfullabai/webhook-notifications

# PNPM
pnpm add @mindfullabai/webhook-notifications

🔧 Utilizzo

TypeScript

import { WebhookClient, creaWebhookClient, WebhookOptions } from '@mindfullabai/webhook-notifications';

// Opzioni di configurazione
const options: WebhookOptions = {
  webhookUrl: 'https://api.telegram.org/bot<TOKEN>/sendMessage',
  chatId: '-123456789',
  timeout: 5000,
  retryAttempts: 3,
  retryDelay: 1000,
  debug: true
};

// Creazione del client
const client = new WebhookClient(options);
// oppure usando la factory function
const client = creaWebhookClient(options);

// Test di connettività
const testResult = await client.test();
console.log('Connessione:', testResult.success ? '✅' : '❌');

// Registrazione utente semplice
const result = await client.registrazioneUtente('mario@example.com');

// Registrazione utente con dati extra
const extraData = {
  nome: 'Mario',
  cognome: 'Rossi',
  telefono: '+39123456789',
  azienda: 'MindfullabAI',
  paese: 'Italia'
};
await client.registrazioneUtente('mario@example.com', extraData);

// Notifica nuovo ordine
await client.nuovoOrdine('ORD-001', 'mario@example.com', 199.99, 'EUR', {
  prodotti: [
    { nome: 'Prodotto A', quantita: 2, prezzo: 99.99 }
  ],
  indirizzo: {
    via: 'Via Roma 123',
    citta: 'Milano',
    cap: '20100',
    paese: 'Italia'
  }
});

// Notifica errore di sistema
await client.erroreSystema('Database connection failed', 'CRITICAL', {
  server: 'db-01',
  timestamp: new Date().toISOString()
});

// Notifica personalizzata
await client.invia({
  title: 'Titolo Personalizzato',
  message: 'Messaggio di test',
  priority: 'HIGH',
  extra: { custom: 'data' }
});

JavaScript (ES Modules)

// Import con supporto per ES modules
import { WebhookClient, creaWebhookClient } from '@mindfullabai/webhook-notifications/js';

const options = {
  webhookUrl: 'https://api.telegram.org/bot<TOKEN>/sendMessage',
  chatId: '-123456789',
  timeout: 5000,
  retryAttempts: 3,
  debug: true
};

const client = new WebhookClient(options);

// Tutte le stesse funzionalità del TypeScript
// ma con autocompletamento JSDoc invece dei tipi
const result = await client.registrazioneUtente('mario@example.com');
console.log('Registrazione:', result.success ? '✅' : '❌');

JavaScript (CommonJS)

// Import con supporto per CommonJS
const { WebhookClient, creaWebhookClient } = require('@mindfullabai/webhook-notifications/js');

const client = new WebhookClient({
  webhookUrl: 'https://api.telegram.org/bot<TOKEN>/sendMessage',
  chatId: '-123456789'
});

// Async/await
async function inviaNotifica() {
  try {
    const result = await client.nuovoOrdine('ORD-002', 'test@email.com', 149.99, 'EUR');
    console.log('Ordine inviato:', result.messageId);
  } catch (error) {
    console.error('Errore:', error.message);
  }
}

// Promise chains
client.test()
  .then(result => console.log('Test:', result.success))
  .catch(error => console.error('Errore test:', error));

Browser (HTML)

<!DOCTYPE html>
<html>
<head>
  <title>Webhook Client Example</title>
</head>
<body>
  <script type="module">
    // Usa la versione ES modules per il browser
    import { WebhookClient } from 'https://unpkg.com/@mindfullabai/webhook-notifications/dist-js/index.esm.js';
    
    const client = new WebhookClient({
      webhookUrl: 'https://api.telegram.org/bot<TOKEN>/sendMessage',
      chatId: '-123456789'
    });
    
    // Esempio di notifica dal browser
    document.getElementById('notify-btn').addEventListener('click', async () => {
      try {
        const result = await client.invia({
          title: 'Notifica dal Browser',
          message: 'Messaggio inviato dalla pagina web',
          priority: 'MEDIUM'
        });
        console.log('Notifica inviata:', result.success);
      } catch (error) {
        console.error('Errore:', error.message);
      }
    });
  </script>
  
  <button id="notify-btn">Invia Notifica</button>
</body>
</html>

📚 API Reference

WebhookClient

Constructor

new WebhookClient(options: WebhookOptions)

Options

Parametro Tipo Richiesto Default Descrizione
webhookUrl string - URL del webhook (Telegram Bot API)
chatId string - ID del chat/gruppo di destinazione
timeout number 5000 Timeout in millisecondi
retryAttempts number 3 Numero di tentativi di retry
retryDelay number 1000 Delay tra i retry in ms
debug boolean false Abilita logging debug

Metodi

registrazioneUtente(email, extraData?): Promise<WebhookResponse>

Invia una notifica di registrazione utente.

// Semplice
await client.registrazioneUtente('mario@example.com');

// Con dati extra
await client.registrazioneUtente('mario@example.com', {
  nome: 'Mario',
  cognome: 'Rossi',
  telefono: '+39123456789',
  azienda: 'Company',
  paese: 'Italia',
  fonte: 'website',
  note: 'Note aggiuntive'
});
nuovoOrdine(ordineId, email, importo, valuta, dettagli?): Promise<WebhookResponse>

Invia una notifica per un nuovo ordine.

await client.nuovoOrdine('ORD-001', 'mario@example.com', 199.99, 'EUR', {
  prodotti: [
    { nome: 'Prodotto A', quantita: 2, prezzo: 99.99 },
    { nome: 'Prodotto B', quantita: 1, prezzo: 0.01 }
  ],
  indirizzo: {
    via: 'Via Roma 123',
    citta: 'Milano',
    cap: '20100',
    paese: 'Italia'
  },
  metodoPagamento: 'Carta di credito',
  note: 'Consegna rapida'
});
erroreSystema(messaggio, priorita, dettagli?): Promise<WebhookResponse>

Invia una notifica di errore di sistema.

await client.erroreSystema('Database connection failed', 'CRITICAL', {
  error: 'Connection timeout after 30s',
  server: 'db-primary-01',
  timestamp: new Date().toISOString(),
  affectedServices: ['api', 'web']
});

Livelli di priorità:

  • 'LOW' - ℹ️ INFO
  • 'MEDIUM' - ⚠️ ATTENZIONE
  • 'HIGH' - 🔥 ERRORE GRAVE
  • 'CRITICAL' - 🚨 ERRORE CRITICO
invia(payload): Promise<WebhookResponse>

Invia una notifica personalizzata.

await client.invia({
  title: 'Titolo Personalizzato',
  message: 'Messaggio dettagliato',
  priority: 'HIGH',
  extra: {
    userId: '12345',
    action: 'custom_action',
    metadata: { custom: 'data' }
  }
});
test(): Promise<WebhookResponse>

Testa la connettività del webhook.

const result = await client.test();
console.log(`Connessione: ${result.success ? 'OK' : 'FAILED'}`);
console.log(`Tempo di risposta: ${result.responseTime}ms`);

Factory Function

const client = creaWebhookClient(options);
// Equivalente a: new WebhookClient(options)

🔧 Sviluppo

Setup locale

git clone https://github.com/mindfullabai/webhook-notifications.git
cd webhook-notifications
npm install

Build

# Build completo (TypeScript + JavaScript)
npm run build

# Build solo TypeScript
npm run build:ts

# Build solo JavaScript  
npm run build:js

# Pulizia build
npm run clean

Testing

# Test completi
npm test

# Test solo TypeScript
npm run test:ts

# Test solo JavaScript
npm run test:js

# Test con coverage
npm test -- --coverage

Esempi

# Esegui esempio Node.js
npm run start:example

# Esegui esempio Express.js
npm run start:express

🔍 Troubleshooting

Errori comuni

"URL webhook non valida"

Verifica che l'URL del webhook sia nel formato corretto:

https://api.telegram.org/bot<TOKEN>/sendMessage

"Chat ID non può essere vuoto"

Assicurati di fornire un Chat ID valido. Per i gruppi, deve iniziare con -.

"Formato email non valido"

L'email deve essere nel formato standard user@domain.com.

"Network timeout"

Aumenta il valore di timeout nelle opzioni o verifica la connettività di rete.

Debug

Abilita il debug per vedere i log dettagliati:

const client = new WebhookClient({
  webhookUrl: 'your-webhook-url',
  chatId: 'your-chat-id',
  debug: true  // ← Abilita debug
});

📄 Licenza

MIT © MindfullabAI

🤝 Contribuzioni

Le contribuzioni sono benvenute! Vedi CONTRIBUTING.md per i dettagli.

📞 Supporto

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages