SDK JavaScript

SDK JavaScript

L'SDK ufficiale JavaScript per CrowdHandler https://www.crowdhandler.com, dedicato alla gestione delle sale d'attesa e delle code. Funziona sia in ambiente Node.js che nel browser.

  • Facile integrazione: aggiungi la gestione delle code a qualsiasi applicazione JavaScript con una singola chiamata di funzione
  • Implementazione flessibile - Funziona su server Node.js, browser, Lambda@Edge, Cloudflare Workers e altri ambienti di esecuzione edge
  • Opzioni di prestazione - Scegli tra la convalida tramite API in tempo reale e la convalida locale della firma, in base alle tue esigenze
  • Continuità della coda - Mantiene la posizione dell'utente anche in caso di aggiornamento della pagina e tra una sessione e l'altra
  • Supporto per TypeScript - Definizioni complete dei tipi per un'esperienza di sviluppo ottimale
  • Accesso all'API - Gestisci le sale d'attesa, monitora le code e accedi alle analisi in modo programmatico

Installazione

npm install crowdhandler-sdk

<!-- Load from unpkg -->
<script src="https://unpkg.com/crowdhandler-sdk/dist/crowdhandler.umd.min.js"></script>

<!-- Or specify a version -->
<script src="https://unpkg.com/crowdhandler-sdk@2.4.0/dist/crowdhandler.umd.min.js"></script>

dei moduli#

L'SDK è disponibile in diversi formati:

  • Moduli ES - import { init } da 'crowdhandler-sdk'
  • CommonJS - const crowdhandler = require('crowdhandler-sdk')
  • UMD - Disponibile come window.crowdhandler quando viene caricato tramite il tag script
  • Importazione dinamica - await import('crowdhandler-sdk')

rapida#

Node.js /

const crowdhandler = require('crowdhandler-sdk');
// or ES modules: import { init } from 'crowdhandler-sdk';

// Initialize SDK
const { client, gatekeeper } = crowdhandler.init({
  publicKey: 'YOUR_PUBLIC_KEY',
  // Optional: add privateKey for private API access
  privateKey: 'YOUR_PRIVATE_KEY',
  request: req,  // Express request object
  response: res  // Express response object
});

// Validate the request
const result = await gatekeeper.validateRequest();

// Check for errors first
if (result.error) {
  console.error(`Validation error: ${result.error.message}`);
  // 4xx errors: promoted = false (always block access)
  // 5xx errors: promoted depends on trustOnFail setting
}

// Handle the validation result
if (result.setCookie) {
  gatekeeper.setCookie(result.cookieValue, result.domain);
}

if (result.stripParams) {
  return gatekeeper.redirectToCleanUrl(result.targetURL);
}

if (!result.promoted) {
  return gatekeeper.redirectIfNotPromoted();
}

// User is promoted - continue with your application
// ... your protected content here ...

// Record performance (optional but recommended)
await gatekeeper.recordPerformance();

Browser /

// Using script tag
const { client, gatekeeper } = window.crowdhandler.init({
  publicKey: 'YOUR_PUBLIC_KEY',
  options: {
    mode: 'clientside'
  }
});

// Or using ES Modules
import { init } from 'crowdhandler-sdk';
const { client, gatekeeper } = init({
  publicKey: 'YOUR_PUBLIC_KEY',
  options: {
    mode: 'clientside'
  }
});

// Validate the request
const result = await gatekeeper.validateRequest();

// Handle the validation result
if (result.setCookie) {
  gatekeeper.setCookie(result.cookieValue, result.domain);
}

if (result.stripParams) {
  // Redirect to clean URL
  window.location.href = result.targetURL;
  return;
}

if (!result.promoted) {
  // Redirect to waiting room
  gatekeeper.redirectIfNotPromoted();
  return;
}

// User is promoted - your application continues
console.log('User granted access');

// Record performance (optional but recommended)
await gatekeeper.recordPerformance();

Cloudflare

import { init } from 'crowdhandler-sdk';

export default {
  async fetch(request, env, ctx) {
    const { gatekeeper } = init({
      publicKey: env.CROWDHANDLER_PUBLIC_KEY,
      cloudflareWorkersRequest: request
    });

    const result = await gatekeeper.validateRequest();

    // Workers have no mutable response object — build the outgoing
    // Response yourself using values from the result.
    if (!result.promoted) {
      return new Response(null, {
        status: 302,
        headers: { Location: result.targetURL }
      });
    }

    const originResponse = await fetch(request);
    const response = new Response(originResponse.body, originResponse);

    if (result.setCookie) {
      response.headers.append(
        'set-cookie',
        `crowdhandler=${result.cookieValue}; path=/; Secure`
      );
    }

    ctx.waitUntil(gatekeeper.recordPerformance());
    return response;
  }
};

fondamentali#

gatekeeper.validateRequest(params?)

Il metodo principale per la convalida delle richieste rispetto al sistema di code di CrowdHandler. Questo metodo determina se a un utente debba essere concesso l'accesso alla risorsa protetta o se debba essere indirizzato a una sala d'attesa.

// Basic usage
const result = await gatekeeper.validateRequest();

// With custom parameters
const result = await gatekeeper.validateRequest({
  custom: {
    code: 'ABC123',
    captcha: 'xK9mN2pQ5vL8wR3tY6uZ1aS4dF7gH0j'
  }
});

Parametri:

  • parametri (facoltativo) - Oggetto contenente parametri personalizzati
    • personalizzato - Oggetto contenente eventuali coppie chiave-valore da inviare all'API CrowdHandler

Come funziona:

  1. Verifica del token: verifica innanzitutto se nei cookie è presente un token di sessione CrowdHandler
  2. Convalida API: invia il token (o ne genera uno nuovo) all'API di CrowdHandler, includendo eventuali parametri personalizzati
  3. Posizione nella coda: determina se l'utente viene fatto avanzare in base alla capacità attuale
  4. Risposta: Fornisce le istruzioni su come gestire la richiesta

Oggetto restituito:

{
  promoted: boolean,      // true = grant access, false = send to waiting room
  setCookie: boolean,     // true = update the user's session cookie
  cookieValue: string,    // The session token to store in the cookie
  stripParams: boolean,   // true = remove CrowdHandler URL parameters
  targetURL: string,      // Where to redirect (clean URL or waiting room)
  slug: string,           // The waiting room slug (when not promoted)
  responseID: string,     // Response ID for performance tracking (when promoted)
  deployment: string,     // Deployment identifier from the API
  token: string,          // The session token
  hash: string | null,    // Signature hash for validation (when available)
  requested: string,      // Timestamp when the request was made
  liteValidatorRedirect: boolean,  // true = redirect to lite validator
  liteValidatorUrl: string         // URL for lite validator redirect
}

Comportamento specifico per modalità:

  • Modalità completa (impostazione predefinita): effettua una chiamata API ad ogni richiesta per la convalida in tempo reale
  • Modalità ibrida: verifica le firme a livello locale per gli utenti con privilegi avanzati, riducendo il numero di chiamate API
  • Modalità lato client: la convalida avviene interamente nel browser tramite cookie

Gestione degli errori:

try {
  const result = await gatekeeper.validateRequest();
  // ... handle result ...
} catch (error) {
  console.error('Validation failed:', error.message);
  console.error('Status code:', error.statusCode);
  // Handle based on trustOnFail setting
}

### gatekeeper.setCookie(value, domain?)

Sets the CrowdHandler session cookie. Always call this when `result.setCookie` is true to maintain the user's queue position. The optional `domain` parameter (provided in `result.domain`) enables proper cookie scoping for wildcard domains.

```javascript
if (result.setCookie) {
  gatekeeper.setCookie(result.cookieValue, result.domain);
}

gatekeeper.redirectToCleanUrl(url)

Rimuove i parametri di tracciamento di CrowdHandler dagli URL. Da utilizzare quando result.stripParams È importante mantenere gli URL chiari e semplici.

if (result.stripParams) {
  return gatekeeper.redirectToCleanUrl(result.targetURL);
}

gatekeeper.redirectIfNotPromoted()

Metodo pratico che gestisce l'intero flusso di reindirizzamento per gli utenti non promossi. Gestisce automaticamente i cookie e i reindirizzamenti.

if (!result.promoted) {
  return gatekeeper.redirectIfNotPromoted();
}

gatekeeper.redirectIfPromoted()

Reindirizza gli utenti promossi da un'implementazione "sala d'attesa" al sito di destinazione con parametri CrowdHandler aggiornati. Questo metodo è specificamente destinato all'uso nelle implementazioni "sala d'attesa".

// In waiting room implementation
if (result.promoted) {
  return gatekeeper.redirectIfPromoted();
}

Caso d'uso: quando si crea una sala d'attesa personalizzata che gira sulla propria infrastruttura, questo metodo gestisce il reindirizzamento alla risorsa protetta con i parametri CrowdHandler corretti.

gatekeeper.recordPerformance(options?)

Registra i parametri di prestazione per aiutare CrowdHandler a ottimizzare il flusso e la capacità delle code.

// Simple usage (recommended)
await gatekeeper.recordPerformance();

// With custom options
await gatekeeper.recordPerformance({
  sample: 1,             // Record 100% of requests (default 0.2)
  statusCode: 200,       // HTTP status code (default 200)
  overrideElapsed: 1234, // Custom timing in ms
  timeout: 1500          // Per-call API timeout in ms (default 1500)
});

gatekeeper.overrideWaitingRoomUrl(url)

Sostituisce la sala d'attesa predefinita di CrowdHandler con il tuo URL personalizzato.

// Redirect to your custom queue page
gatekeeper.overrideWaitingRoomUrl('https://mysite.com/custom-queue');

di inizializzazione#

const instance = crowdhandler.init({
  // Required
  publicKey: 'YOUR_PUBLIC_KEY',
  
  // Optional
  privateKey: 'YOUR_PRIVATE_KEY',  // Required for private API methods
  
  // Request context (choose one based on your environment)
  request: req,                       // Express/Node.js request
  response: res,                      // Express/Node.js response
  lambdaEdgeEvent: event,             // Lambda@Edge event
  cloudflareWorkersRequest: request,  // Cloudflare Workers Request
  // (none)                           // Browser environment (auto-detected)
  
  // Options
  options: {
    mode: 'full',         // 'full' (default), 'hybrid', 'clientside'
    apiUrl: 'https://api.crowdhandler.com',  // Custom API endpoint
    debug: false,         // Enable debug logging
    timeout: 5000,        // API timeout in milliseconds
    trustOnFail: true,    // Allow access if API fails
    fallbackSlug: '',     // Fallback room slug when trustOnFail is false
    cookieName: 'crowdhandler',  // Custom cookie name (default: 'crowdhandler')
    cookieMaxAgeSeconds: 86400,  // Optional. Persist the cookie via Max-Age (seconds).
                                 // Omit for a session cookie (default).
    forceCloudflareWorkers: true,  // Optional. Bypass navigator-based runtime inference
                                   // and treat the runtime as Cloudflare Workers. Only `true`
                                   // is accepted; omit for auto-detection.
    waitingRoom: false,   // Set to true if SDK is running in a waiting room context
    liteValidator: false, // Enable lite validator mode (default: false)
    roomsConfig: [{       // Array of room configurations for lite validator
      domain: string,     // e.g. 'https://example.com'
      slug: string,       // Room identifier
      urlPattern?: string,  // URL pattern to match
      patternType?: 'regex' | 'contains' | 'all',
      queueActivatesOn?: number,  // Unix timestamp
      timeout?: number    // Timeout in seconds
    }]
  }
});

di convalida#

Modalità completa (predefinita)

La soluzione ideale per la maggior parte delle integrazioni lato server.

  • Vantaggi: configurazione semplice, non richiede una chiave privata, funzionalità complete
  • Svantaggi: chiamata API ad ogni richiesta (latenza di 20-100 ms)

ibrida#

Per applicazioni in cui le prestazioni sono fondamentali.

  • Vantaggi: latenza minima (2-10 ms), minor numero di chiamate API
  • Svantaggi: richiede una chiave privata e l'uso di JavaScript lato client per le funzionalità aggiuntive
const instance = crowdhandler.init({
  publicKey: 'YOUR_PUBLIC_KEY',
  privateKey: 'YOUR_PRIVATE_KEY',  // Required for hybrid mode
  options: { mode: 'hybrid' }
});

lato client#

Per applicazioni a pagina singola e siti statici.

  • Vantaggi: funziona senza server, facile da integrare
  • Svantaggi: funziona solo sul lato client, richiede JavaScript

cookie personalizzato#

Per impostazione predefinita, CrowdHandler utilizza addetto alla gestione della folla come nome del cookie. È possibile sovrascrivere questo valore con un nome personalizzato:

const { gatekeeper } = crowdhandler.init({
  publicKey: 'YOUR_PUBLIC_KEY',
  options: {
    cookieName: 'my-custom-queue'  // Use custom cookie name
  }
});

Questo è utile quando:

  • Esecuzione di più istanze di CrowdHandler sullo stesso dominio
  • Come evitare conflitti con i cookie esistenti
  • Rispetto di specifiche convenzioni di denominazione

dei cookie#

Per impostazione predefinita, il cookie CrowdHandler è un cookie di sessione — il browser lo elimina quando l'utente chiude completamente la sessione (nota: molti browser ripristinano i cookie di sessione se è abilitata l'opzione "riprendi da dove avevi interrotto"). Per i casi d'uso relativi alle sale d'attesa in cui si desidera che la posizione di un utente in coda venga mantenuta anche dopo il riavvio del browser, è necessario attivare la persistenza con cookieMaxAgeSeconds:

const { gatekeeper } = crowdhandler.init({
  publicKey: 'YOUR_PUBLIC_KEY',
  options: {
    cookieMaxAgeSeconds: 86400  // Persist for 24 hours via Max-Age
  }
});

Note:

  • Il valore viene scritto come parte del cookie Max-Age attributo (da preferire rispetto a Scadenza (poiché non risente dello scostamento dell'orologio del client).
  • L'opzione si applica a ogni Set-Cookie generato dall'SDK, sia mentre l'utente è in coda sia dopo la promozione.
  • Ometti l'opzione (oppure lasciala non definito) per mantenere il comportamento originale del cookie di sessione.

Forzare il di Cloudflare Workers#

L'SDK ricava un runtime di Cloudflare Workers da navigator.userAgent. Se quel segnale non è affidabile nel tuo ambiente (build personalizzate di workerd, bundler che rimuovono le variabili globali, framework di test), puoi rendere esplicita la decisione:

const { gatekeeper } = crowdhandler.init({
  publicKey: env.CROWDHANDLER_PUBLIC_KEY,
  cloudflareWorkersRequest: request,
  options: {
    forceCloudflareWorkers: true
  }
});

Solo vero viene accettata — ometti l'opzione per ricorrere al rilevamento automatico. Con debug: true, l'SDK registra quale segnale ha determinato la decisione, ad esempio: [CH] Runtime di Cloudflare Workers: true (tramite override) vs (tramite inferenza del navigatore). L'override viene azzerato ad ogni init() chiamata in modo che non vi siano mai perdite durante le reinizializzazioni.

API#

L'SDK fornisce un client unificato sia per le API pubbliche che per quelle private:

// List all waiting rooms
const rooms = await client.rooms().get();

// Get specific room
const room = await client.rooms().get('room_id');

// Create a new room (requires privateKey)
const newRoom = await client.rooms().post({
  name: 'Product Launch',
  domain: 'example.com'
});

// Update room settings
await client.rooms().put('room_id', {
  capacity: 1000
});

// Delete a room
await client.rooms().delete('room_id');

disponibili#

API pubblica (solo publicKey):

  • client.requests() - Verifica della richiesta
  • client.responses() - Monitoraggio delle risposte
  • client.rooms() - Informazioni sulla sala d'attesa

API privata (richiede una chiave privata):

  • client.account() - Informazioni sull'account
  • client.accountPlan() - Dettagli del piano dell'account
  • client.codes() - Gestione dei codici di accesso
  • client.domains() - Configurazione del dominio
  • client.domainIPs() - Indirizzi IP dei domini
  • client.domainReports() - Analisi dei domini
  • client.domainRequests() - Registri delle richieste relative ai domini
  • client.domainRooms() - Camere per un dominio
  • client.domainURLs() - URL protetti
  • client.groups() - Gruppi di codici di accesso
  • client.groupBatch() - Operazioni relative ai codici lotto
  • client.groupCodes() - Codici in un gruppo
  • client.ips() - Gestione degli indirizzi IP
  • client.reports() - Report analitici
  • client.rooms() - Gestione della sala d'attesa
  • client.roomReports() - Analisi dei dati relativi alle camere
  • client.roomSessions() - Sessioni in aula
  • client.sessions() - Gestione delle sessioni
  • client.templates() - Modelli per sale d'attesa

Tutti i metodi supportano le operazioni REST standard, ove applicabile:

  • .get() - Elencare tutte le risorse o recuperare una risorsa specifica in base all'ID
  • .post(data) - Crea una nuova risorsa
  • .put(id, data) - Aggiornare la risorsa esistente
  • .patch(id, data) - Aggiornamento parziale
  • .delete(id) - Elimina risorsa

La documentazione completa dell'API, con esempi di richieste e risposte, è disponibile nella dashboard di CrowdHandler alla voce Account → API.

degli errori#

Tutti gli errori dell'SDK sono casi di CrowdHandlerError con una struttura coerente:

try {
  const rooms = await client.rooms().get();
} catch (error) {
  console.error(error.message);    // The actual API error message
  console.error(error.statusCode); // HTTP status code (e.g., 401, 404)
  console.error(error.suggestion); // Helpful guidance for resolution
  console.error(error.code);       // Error code for programmatic handling
}

degli errori API#

L'SDK riproduce fedelmente i messaggi di errore dell'API CrowdHandler, consentendo di gestire scenari di errore specifici:

try {
  const result = await gatekeeper.validateRequest({
    custom: { code: 'user-code' }
  });
} catch (error) {
  // Check the specific error message from the API
  if (error.message.includes('Invalid priority code')) {
    // Handle invalid access code
  }
  
  // For advanced debugging, access the full API response
  const apiResponse = error.context?.apiResponse;
}

di errore comuni#

  • CONFIGURAZIONE NON VALIDA - Configurazione SDK non valida
  • MISSING_PRIVATE_KEY - Per questa operazione è necessaria una chiave privata
  • API_CONNESSIONE_FALLITA - Impossibile accedere all'API di CrowdHandler
  • API_RISPOSTA_NON_VALIDA - L'API ha restituito un errore
  • RATE_LIMITED - Troppe richieste (comprese quelle con "retry-after")

di integrazione#

Consulta la directory degli esempi per esempi completi e funzionanti, tra cui:

  • Implementazioni di Express.js (protezione completa, solo API, API privata)
  • Handler Lambda@Edge
  • Integrazione con React
  • Modelli di gestione degli errori
  • Utilizzo di TypeScript

Express.

const express = require('express');
const crowdhandler = require('crowdhandler-sdk');

const app = express();

// Middleware to protect routes
async function protectRoute(req, res, next) {
  try {
    const { gatekeeper } = crowdhandler.init({
      publicKey: process.env.CROWDHANDLER_PUBLIC_KEY,
      request: req,
      response: res
    });

    const result = await gatekeeper.validateRequest();
    
    // Check if there was an error during validation
    if (result.error) {
      console.error(`API Error ${result.error.statusCode}: ${result.error.message}`);
      // 4xx errors (e.g., invalid key, bad request): promoted = false (user blocked)
      // 5xx errors (e.g., server error): promoted based on trustOnFail setting
    }
    
    if (result.setCookie) {
      gatekeeper.setCookie(result.cookieValue, result.domain);
    }
    
    if (result.stripParams) {
      return gatekeeper.redirectToCleanUrl(result.targetURL);
    }
    
    if (!result.promoted) {
      return gatekeeper.redirectIfNotPromoted();
    }
    
    // User is promoted, continue
    res.locals.gatekeeper = gatekeeper;
    next();
  } catch (error) {
    // This catches unexpected errors (e.g., network issues, config errors)
    console.error('CrowdHandler SDK error:', error.message);
    // trustOnFail: true (default) = allow access on error
    // trustOnFail: false = block access on error
    next();
  }
}

// Protect specific routes
app.get('/limited-product', protectRoute, (req, res) => {
  res.send('This is a limited product page!');
  
  // Record performance after response
  if (res.locals.gatekeeper) {
    res.locals.gatekeeper.recordPerformance();
  }
});

const crowdhandler = require('crowdhandler-sdk');

exports.handler = async (event) => {
  const { gatekeeper } = crowdhandler.init({
    publicKey: process.env.CROWDHANDLER_PUBLIC_KEY,
    lambdaEdgeEvent: event
  });

  const result = await gatekeeper.validateRequest();
  
  if (!result.promoted) {
    // Redirect to waiting room
    return {
      status: '302',
      statusDescription: 'Found',
      headers: {
        location: [{
          key: 'Location',
          value: result.targetURL
        }]
      }
    };
  }
  
  // Continue with normal request processing
  return event.Records[0].cf.request;
};

Cloudflare

L'SDK include il supporto nativo per il runtime di Cloudflare Workers (workerd): non sono necessari polyfill per Node. Passa a Workers Richiesta oggetto tramite cloudflareWorkersRequest e l'SDK utilizza il codice nativo recupera internamente per tutte le chiamate API.

import { init } from 'crowdhandler-sdk';

export default {
  async fetch(request, env, ctx) {
    const { gatekeeper } = init({
      publicKey: env.CROWDHANDLER_PUBLIC_KEY,
      cloudflareWorkersRequest: request
    });

    const result = await gatekeeper.validateRequest();

    if (result.error) {
      console.error(`API Error ${result.error.statusCode}: ${result.error.message}`);
    }

    // Strip CrowdHandler params from a freshly promoted URL
    if (result.stripParams) {
      return new Response(null, {
        status: 302,
        headers: {
          Location: decodeURIComponent(result.targetURL),
          'Set-Cookie': `crowdhandler=${result.cookieValue}; path=/; Secure`
        }
      });
    }

    // Send unpromoted users to the waiting room
    if (!result.promoted) {
      return new Response(null, {
        status: 302,
        headers: { Location: result.targetURL }
      });
    }

    // Promoted: fetch the origin and attach the session cookie if needed
    const originResponse = await fetch(request);
    const response = new Response(originResponse.body, originResponse);

    if (result.setCookie) {
      response.headers.append(
        'set-cookie',
        `crowdhandler=${result.cookieValue}; path=/; Secure`
      );
    }

    // Performance recording continues after the response is returned
    ctx.waitUntil(gatekeeper.recordPerformance());
    return response;
  }
};

Workers vs. Express/Lambda — quali sono le differenze:

  • I worker non dispongono di un oggetto di risposta modificabile. Creare il messaggio in uscita Risposta da soli utilizzando i valori provenienti da risultato (cookieValue, URL di destinazione, setCookie) anziché ricorrere a metodi di supporto che modificano la risposta direttamente.
  • Utilizzo ctx.waitUntil() per recordPerformance() in modo che la chiamata alla metrica non ritardi la risposta dell'utente. Sui Worker, l'SDK attende internamente la chiamata all'API sottostante (quindi effettua effettivamente il flush all'interno di ctx.waitUntil); per impostazione predefinita, il limite massimo per il put è di 1500 ms — pass { timeout: <ms> } da mettere a punto.
  • Predefinito modalità: 'completa' (come indicato sopra) richiede solo la chiave pubblica. La modalità ibrida è supportata, ma richiede l'invio della chiave privata come segreto del Worker: procedi in questo modo solo dopo aver valutato i pro e i contro.

React / Next.

import { useEffect, useState } from 'react';
import { init } from 'crowdhandler-sdk';

function ProtectedComponent() {
  const [isPromoted, setIsPromoted] = useState(null);
  
  useEffect(() => {
    const checkAccess = async () => {
      const { gatekeeper } = init({
        publicKey: 'YOUR_PUBLIC_KEY',
        options: { mode: 'clientside' }
      });
      
      const result = await gatekeeper.validateRequest();
      
      if (!result.promoted) {
        window.location.href = result.targetURL;
      } else {
        setIsPromoted(true);
      }
    };
    
    checkAccess();
  }, []);
  
  if (isPromoted === null) return <div>Checking access...</div>;
  if (!isPromoted) return <div>Redirecting to waiting room...</div>;
  
  return <div>Protected content here!</div>;
}

avanzate#

Sovrascrivi della sala d'attesa#

gatekeeper.overrideWaitingRoomUrl('https://custom-wait.example.com');

di esclusione personalizzati#

// Don't check these paths
gatekeeper.setIgnoreUrls(/\.(css|js|png|jpg)$/);

della richiesta di deroga#

gatekeeper.overrideHost('example.com');
gatekeeper.overridePath('/special-path');
gatekeeper.overrideIP('203.0.113.0');
gatekeeper.overrideLang('en-US');
gatekeeper.overrideUserAgent('Custom Bot 1.0');

delle prestazioni#

// Basic usage (records automatically)
await gatekeeper.recordPerformance();

// With options
await gatekeeper.recordPerformance({
  sample: 1.0,           // Record 100% of requests (default 0.2)
  statusCode: 200,       // HTTP status code
  overrideElapsed: 1234, // Custom timing in ms
  timeout: 1500          // Per-call API timeout in ms (default 1500, overrides global SDK timeout)
});

di errori di test#

Per testare la gestione degli errori senza effettuare vere e proprie chiamate all'API, è possibile simulare degli errori:

const { gatekeeper } = init({
  publicKey: 'YOUR_PUBLIC_KEY',
  request: req,
  response: res,
  options: {
    testError: {
      statusCode: 500,  // Simulate a 500 error
      message: 'Simulated server error for testing'
    }
  }
});

// This will return immediately with a simulated error
const result = await gatekeeper.validateRequest();
// result.error will contain the test error
// result.promoted will be true (with default trustOnFail: true)

Questo è utile per:

  • Test della logica di gestione degli errori in fase di sviluppo
  • Verifica del comportamento di fallback per diversi tipi di errore
  • Test di integrazione senza influire sulle metriche di produzione

Nota: gli errori di test con codice 4xx verranno sempre impostati promosso: false, mentre gli errori di test 5xx tengono conto del tuo trustOnFail impostazione.

Lite Validator#

La modalità "Lite Validator" consente di aggiornare i token senza effettuare chiamate API, verificando la configurazione della stanza a livello locale. Per abilitarla:

  1. Set liteValidator: true nelle opzioni
  2. Recupera e fornisci la configurazione delle tue stanze dall'API di CrowdHandler
// First, fetch your rooms configuration
const { client } = init({ publicKey: 'YOUR_PUBLIC_KEY' });
const roomsResponse = await client.rooms().get();

// Then initialize with lite validator enabled
const { gatekeeper } = init({
  publicKey: 'YOUR_PUBLIC_KEY',
  request: req,
  response: res,
  options: {
    liteValidator: true,              // Enable lite validator
    roomsConfig: roomsResponse.result // Pass the rooms array from API
  }
});

// Handle the lite validator redirect
const result = await gatekeeper.validateRequest();

if (result.liteValidatorRedirect) {
  // Redirect to refresh token/session
  return gatekeeper.redirect(result.liteValidatorUrl);
}

Quando Lite Validator si attiva:

  • L'URL corrisponde a una stanza presente nella tua configurazione
  • Il token manca o risale a più di 12 ore fa
  • Reindirizza a CrowdHandler per aggiornare la sessione

L'SDK include strumenti di test completi:

di test locale#

# Avvia il server di test con le tue chiavi
npm run test:server -- --publicKey=LA_TUA_CHIAVE_PUBBLICA --privateKey=LA_TUA_CHIAVE_PRIVATA

# Con opzioni personalizzate
npm run test:server -- --apiUrl=https://staging-api.crowdhandler.com --mode=hybrid

# Modalità di sviluppo (ricostruzione automatica dell'SDK)
npm run test:server:dev

di test del browser n. #

  1. Avvia il server di prova
  2. Apri http://localhost:3000/test/browser-test.html
  3. Test interattivi con integrazione reale delle API

di prova n

# Eseguire i test automatizzati sul server di test
npm run test:client

per TypeScript#

Supporto completo di TypeScript con definizioni dei tipi incluse:

import { init, CrowdHandlerError, ErrorCodes } from 'crowdhandler-sdk';
import type { Mode, Room, Domain, ValidationResult } from 'crowdhandler-sdk';

// All types are properly inferred
const { client, gatekeeper } = init({
  publicKey: 'YOUR_KEY'
});

// TypeScript knows this returns Room[]
const rooms = await client.rooms().get();

// Error handling with types
try {
  await client.domains().get();
} catch (error) {
  if (error instanceof CrowdHandlerError) {
    if (error.code === ErrorCodes.MISSING_PRIVATE_KEY) {
      // Handle missing key
    }
  }
}

sulla build#

L'SDK è disponibile in diversi formati:

  • CommonJS (dist/crowdhandler.cjs.js) - Per Node.js require()
  • Moduli ES (dist/crowdhandler.esm.js) - Per i moderni importa
  • UMD (dist/crowdhandler.umd.js) - Per i browser tramite <script>
  • UMD in versione ridotta (dist/crowdhandler.umd.min.js) - Versione di produzione del browser