CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-aws-amplify--api

A unified API layer for AWS Amplify that combines GraphQL and REST API functionality

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

realtime-events.mddocs/

Real-time and Events

Event system for managing real-time functionality including WebSocket connections and subscription lifecycle management.

Capabilities

Events Channel

Core event system for managing real-time subscriptions and event publishing.

/**
 * Global events channel for real-time functionality
 */
const events: EventsChannel;

interface EventsChannel {
  /**
   * Subscribe to events with an observer
   * @param observer - Observer to handle events
   * @param options - Optional subscription configuration
   * @returns Subscription object for managing the subscription
   */
  subscribe(observer: Observer, options?: EventsOptions): Subscription;
  
  /**
   * Publish an event to the channel
   * @param event - Event data to publish
   * @param options - Optional publish configuration
   * @returns Promise that resolves when event is published
   */
  publish(event: Event, options?: EventsOptions): Promise<any>;
  
  /**
   * Close the channel and all subscriptions
   */
  close(): void;
}

Usage Examples:

import { events } from "@aws-amplify/api";

// Subscribe to events
const subscription = events.subscribe({
  next: (event) => {
    console.log("Received event:", event);
  },
  error: (error) => {
    console.error("Event error:", error);
  },
  complete: () => {
    console.log("Event stream completed");
  }
});

// Publish an event
await events.publish({
  type: "user-action",
  data: { userId: "123", action: "login" }
});

// Clean up
subscription.unsubscribe();

Event Options

Configuration options for event operations.

interface EventsOptions {
  /**
   * Authentication mode for the event operation
   */
  authMode?: GraphQLAuthMode;
  
  /**
   * Custom authentication token
   */
  authToken?: string;
  
  /**
   * Additional headers for the event request
   */
  headers?: Record<string, string>;
  
  /**
   * Event filter criteria
   */
  filter?: EventFilter;
  
  /**
   * Custom user agent details
   */
  userAgentSuffix?: string;
}

interface EventFilter {
  /**
   * Event types to include
   */
  types?: string[];
  
  /**
   * Custom filter function
   */
  predicate?: (event: Event) => boolean;
}

Observer Pattern

Standard observer interface for handling event streams.

interface Observer {
  /**
   * Handle next event in the stream
   * @param event - The event data
   */
  next: (event: Event) => void;
  
  /**
   * Handle errors in the event stream
   * @param error - The error that occurred
   */
  error?: (error: Error) => void;
  
  /**
   * Handle completion of the event stream
   */
  complete?: () => void;
}

interface Subscription {
  /**
   * Unsubscribe from the event stream
   */
  unsubscribe(): void;
  
  /**
   * Check if subscription is closed
   */
  closed: boolean;
}

Connection State Management

WebSocket connection state tracking and management.

/**
 * Constant for connection state change events
 */
const CONNECTION_STATE_CHANGE: string;

/**
 * Enumeration of possible connection states
 */
enum ConnectionState {
  Connected = "Connected",
  ConnectedPendingNetwork = "ConnectedPendingNetwork", 
  ConnectionDisrupted = "ConnectionDisrupted",
  ConnectionDisruptedPendingNetwork = "ConnectionDisruptedPendingNetwork",
  Connecting = "Connecting",
  ConnectedPendingDisconnect = "ConnectedPendingDisconnect",
  Disconnected = "Disconnected",
  ConnectedPendingKeepAlive = "ConnectedPendingKeepAlive"
}

Usage Examples:

import { events, CONNECTION_STATE_CHANGE, ConnectionState } from "@aws-amplify/api";

// Monitor connection state changes
const connectionSubscription = events.subscribe({
  next: (event) => {
    if (event.type === CONNECTION_STATE_CHANGE) {
      const { connectionState } = event.data;
      
      switch (connectionState) {
        case ConnectionState.Connected:
          console.log("WebSocket connected");
          break;
        case ConnectionState.Disconnected:
          console.log("WebSocket disconnected");
          break;
        case ConnectionState.Connecting:
          console.log("WebSocket connecting...");
          break;
        case ConnectionState.ConnectionDisrupted:
          console.log("Connection disrupted, attempting to reconnect");
          break;
      }
    }
  }
});

Event Types

Structure of events in the system.

interface Event {
  /**
   * Event type identifier
   */
  type: string;
  
  /**
   * Event payload data
   */
  data: any;
  
  /**
   * Event timestamp
   */
  timestamp?: number;
  
  /**
   * Event source identifier
   */
  source?: string;
  
  /**
   * Event correlation ID for tracking
   */
  correlationId?: string;
}

/**
 * Common event types used in the system
 */
interface SystemEventTypes {
  CONNECTION_STATE_CHANGE: "connectionStateChange";
  SUBSCRIPTION_ACK: "subscriptionAck";
  SUBSCRIPTION_ERROR: "subscriptionError"; 
  DATA_EVENT: "dataEvent";
  KEEP_ALIVE: "keepAlive";
}

Real-time Subscriptions

Integration with GraphQL subscriptions for real-time data updates.

/**
 * Observable type for real-time data streams
 */
type Observable<T> = {
  subscribe(observer: {
    next: (value: T) => void;
    error?: (error: Error) => void;
    complete?: () => void;
  }): Subscription;
  
  subscribe(
    next: (value: T) => void,
    error?: (error: Error) => void,
    complete?: () => void
  ): Subscription;
};

/**
 * Real-time subscription result
 */
interface SubscriptionResult<T> {
  /**
   * The WebSocket provider managing the connection
   */
  provider: AWSAppSyncRealTimeProvider;
  
  /**
   * The subscription data
   */
  value: GraphQLResult<T>;
}

Usage Examples:

import { generateClient } from "@aws-amplify/api";

const client = generateClient<Schema>();

// Subscribe to real-time updates
const subscription = client.models.Todo.onCreate().subscribe({
  next: ({ data }) => {
    console.log("New todo created:", data);
  },
  error: (error) => {
    console.error("Subscription error:", error);
  }
});

// Clean up subscription
subscription.unsubscribe();

Error Handling

Real-time specific error handling and recovery.

/**
 * Real-time connection errors
 */
interface ConnectionError extends Error {
  /**
   * Error code for categorization
   */
  code?: string;
  
  /**
   * Connection state when error occurred
   */
  connectionState?: ConnectionState;
  
  /**
   * Whether the error is recoverable
   */
  recoverable?: boolean;
  
  /**
   * Suggested retry delay in milliseconds
   */
  retryDelay?: number;
}

/**
 * Subscription-specific errors
 */
interface SubscriptionError extends Error {
  /**
   * Subscription that failed
   */
  subscription?: string;
  
  /**
   * GraphQL errors if applicable
   */
  graphQLErrors?: GraphQLError[];
  
  /**
   * Network error details
   */
  networkError?: Error;
}

docs

graphql-client.md

index.md

realtime-events.md

rest-api.md

server-apis.md

tile.json