Skip to content

API Reference

Zahra Bayat edited this page Sep 13, 2025 · 2 revisions

fire

Asynchronously triggers an event, runs interceptors and middlewares, and executes all handlers with a chosen strategy.

async fire<K extends keyof E>(
  event: K,
  payload: E[K],
  options?: FlareFireOptions
): Promise<string | void>

Parameters

  • event (K extends keyof E) Event name, constrained by your event map E.

  • payload (E[K]) Data associated with the event. The type is inferred from E[event].

  • options (FlareFireOptions, optional) Controls execution strategy and error handling:

    • strategy?: FlareFireStrategyParallel (default) or Sequential.
    • timeout?: number → max time per handler (ms).
    • haltOnError?: boolean → stop on error (true), or continue (false, default).

Return

  • Resolves to void if executed normally.

  • Returns a message (string) if:

    • event was stopped by middleware, or
    • no handlers were found.

Execution Flow

  1. Before interceptors → may stop event early.
  2. Middlewares → can mutate payload or cancel event.
  3. Handlers → executed in parallel or sequential order.
  4. After interceptors → always run after handlers.

Examples

// Fire event in parallel (default)
await fire("userLogin", { id: "u1" });

// Sequential execution with error halting
await fire("dataSync", { items: [1, 2, 3] }, {
  strategy: FlareFireStrategy.Sequential,
  haltOnError: true,
});

// With timeout
await fire("processJob", { jobId: "123" }, { timeout: 5000 });

catch

Registers a handler for an event. Optionally, the handler can run only once.

catch<K extends keyof E>(
  event: K,
  handler: FlareHandler<E[K]>,
  options?: FlareCatchOptions
): () => void

Parameters

  • event (K extends keyof E) Event name, must exist in your E event map.

  • handler ((payload: E[K]) => void | Promise<void>) Function called when the event is fired. Can be synchronous or asynchronous.

  • options (FlareCatchOptions, optional) Optional settings for handler registration:

    • once?: boolean → if true, the handler is automatically removed after the first execution.

Return

  • Returns a release function: calling it unregisters this handler from the event.

Behavior

  • If once: true is set, the handler is wrapped internally so it automatically unregisters after the first call.
  • Multiple handlers for the same event are supported — they are stored in a Set to prevent duplicates.
  • Handlers can be removed anytime using the release function or the release(event, handler) API.

Examples

// Register a normal handler
const releaseHandler = flare.catch("login", (payload) => {
  console.log(`User logged in: ${payload.name}`);
});

// Register a handler that runs only once
flare.catch("signup", (payload) => {
  console.log(`New signup: ${payload.name}`);
}, { once: true });

// Later, manually unregister a handler
releaseHandler();

Notes / Best Practices

  • Use once: true for event handlers that should only run once, e.g., onboarding steps.
  • Keep track of release functions to unregister handlers if they are no longer needed to avoid memory leaks.
  • Multiple handlers can coexist for the same event; order of execution is not guaranteed.

release

Removes a specific handler from an event.

release<K extends keyof E>(
  event: K,
  handler: FlareHandler<E[K]>
): void

Parameters

  • event (K extends keyof E) The event name the handler was registered for.

  • handler (FlareHandler<E[K]>) The exact handler function you want to remove. It must match the one passed to catch.


Behavior

  • Deletes the handler from the event’s internal handler set.
  • If the handler is not registered, nothing happens.
  • Use this to clean up specific handlers without affecting others.

Example

const handler = (payload: { name: string }) => console.log(payload.name);

// Register handler
flare.catch("login", handler);

// Remove handler manually
flare.release("login", handler);

Notes / Best Practices

  • Keep references to handler functions if you plan to release them manually.
  • Prefer using the release function returned by catch for convenience.

releaseAll

Removes all handlers for all events.

releaseAll(): void

Behavior

  • Clears all handlers across all events.
  • Effectively resets the Flare instance’s handler storage.
  • Does not remove interceptors or middlewares.

Example

// Clear all registered handlers
flare.releaseAll();

Notes / Best Practices

  • Useful for full cleanup before destroying a Flare instance or when resetting state.
  • Ensures no memory leaks from lingering handlers.

use

Registers a middleware to run before handlers of an event. Middlewares can modify the payload, stop the event, or perform side effects like logging.

use(middleware: FlareMiddleware<E>): void

Middleware Signature

(context: {
  event: K;
  payload: E[K];
  stop: () => void;
  set: (newPayload: E[K]) => void;
}, next: () => Promise<void>) => void | Promise<void>
  • context.event – the event name.
  • context.payload – current payload for this event.
  • context.stop() – stop event propagation; handlers will not run.
  • context.set(newPayload) – replace the payload before handlers run.
  • next() – call to continue to the next middleware or handlers.

Behavior

  • Middlewares are executed in registration order.
  • If stop() is called, fire resolves early with a cancellation message.
  • Can mutate the payload with set(); handlers receive the new payload.
  • Works with async functions — fire waits for all middlewares to complete before running handlers.

Examples

// Transform payload before handlers
flare.use(({ payload, set, next }) => {
  set({ ...payload, name: payload.name.toUpperCase() });
  return next();
});

// Stop event if condition fails
flare.use(({ payload, stop, next }) => {
  if (!payload.userId) stop();
  return next();
});

Notes / Best Practices

  • Use middlewares for validation, logging, or payload transformation.
  • Keep middlewares small and composable.
  • Middlewares cannot access handlers directly — they operate before handlers.

in

Registers an interceptor for an event. Interceptors wrap the event lifecycle and run before and/or after handlers.

in(interceptor: FlareInterceptor<E>): void

Interceptor Signature

interface FlareInterceptor<E> {
  id?: string;
  before?(event: keyof E, payload: E[keyof E]): boolean | void;
  after?(event: keyof E, payload: E[keyof E]): void;
}
  • before(event, payload) – runs before handlers.

    • Return false to cancel the event.
  • after(event, payload) – runs after all handlers have executed.

  • id – optional identifier for logging or debugging.


Behavior

  • before interceptors run in registration order.
  • If any before returns false, fire resolves early with a cancellation message.
  • after interceptors run after all handlers, regardless of strategy.
  • Does not modify payload unless combined with middleware.

Examples

// Log before and after events
flare.in({
  id: "logger",
  before(event, payload) {
    console.log("Before", event, payload);
  },
  after(event, payload) {
    console.log("After", event, payload);
  }
});

// Cancel event if user is missing
flare.in({
  before(event, payload) {
    if (!payload.user) return false;
  }
});

Notes / Best Practices

  • Use interceptors for cross-cutting concerns like logging, analytics, authentication.
  • Prefer interceptors over middlewares if the logic is not related to payload transformation.
  • Interceptors cannot prevent other interceptors from running — only before can cancel the event.