or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

application.mdauthentication.mderror-handling.mdindex.mdrest-transport.mdservices.mdsocketio-transport.md
tile.json

socketio-transport.mddocs/

Socket.IO Transport

Real-time WebSocket transport using Socket.io for live data synchronization and event-driven communication with automatic event handling and service method integration.

Capabilities

Socket.IO Client Factory

Configure Socket.IO transport for real-time communication with the server.

/**
 * Configure Socket.IO transport
 * @param socket - Socket.io client instance
 * @param options - Optional configuration options
 * @returns Transport connection function
 */
function socketio(socket: Socket, options?: any): TransportConnection;

interface TransportConnection<Services = any> {
  (app: Application): void;
}

Usage Examples:

import feathers from "@feathersjs/client";
import { socketio } from "@feathersjs/client";
import io from "socket.io-client";

const app = feathers();

// Basic Socket.IO configuration
const socket = io("http://localhost:3030");
app.configure(socketio(socket));

// With Socket.IO options
const socketWithOptions = io("http://localhost:3030", {
  transports: ["websocket"],
  upgrade: false
});
app.configure(socketio(socketWithOptions));

// With custom options
app.configure(socketio(socket, {
  timeout: 10000
}));

Real-time Service Operations

Socket services extend standard service operations with real-time event handling.

/**
 * Socket.IO service with real-time capabilities
 * Extends standard service interface with event emitter methods
 */
interface SocketService<T = any, D = Partial<T>, P extends Params = Params> extends FeathersService<T, D, P> {
  /** Service path/name */
  path: string;
  
  /** Connection object */
  connection: any;
  
  /** Service method name for internal use */
  method: string;
  
  /** Array of supported events */
  events: string[];
  
  /** Add event listener */
  on(event: string, listener: Function): this;
  
  /** Remove event listener */
  off(event: string, listener?: Function): this;
  
  /** Emit event to server */
  emit(event: string, ...args: any[]): this;
  
  /** Add event listener (alias for on) */
  addListener(event: string, listener: Function): this;
  
  /** Remove specific event listener */
  removeListener(event: string, listener: Function): this;
  
  /** Remove all listeners for an event */
  removeAllListeners(event?: string): this;
  
  /** Execute once and remove listener */
  once(event: string, listener: Function): this;
  
  /** Get listeners for an event */
  listeners(event: string): Function[];
  
  /** Get listener count for an event */
  listenerCount(event: string): number;
  
  /** Send method call to server via socket */
  send<X = any>(method: string, ...args: any[]): Promise<X>;
}

Usage Examples:

const userService = app.service("users");

// Standard service operations work the same
const users = await userService.find();
const user = await userService.get(123);

// Plus real-time event handling
userService.on("created", (user) => {
  console.log("New user created:", user);
});

userService.on("updated", (user) => {
  console.log("User updated:", user);
});

userService.on("removed", (user) => {
  console.log("User removed:", user);
});

Automatic Service Events

Socket services automatically receive real-time events for service operations.

Standard Service Events:

EventTriggered WhenData
createdResource is createdCreated resource
updatedResource is updated (PUT)Updated resource
patchedResource is patchedPatched resource
removedResource is removedRemoved resource

Usage Examples:

const messageService = app.service("messages");

// Listen for new messages
messageService.on("created", (message) => {
  // Real-time message received
  addMessageToUI(message);
});

// Listen for message updates
messageService.on("updated", (message) => {
  updateMessageInUI(message);
});

// Listen for message deletions
messageService.on("removed", (message) => {
  removeMessageFromUI(message);
});

// Listen for all events on a service
messageService.on("*", (event, data) => {
  console.log(`Message service event: ${event}`, data);
});

Event Listener Management

Manage event listeners with various methods for adding, removing, and querying listeners.

/**
 * Add event listener
 * @param event - Event name to listen for
 * @param listener - Function to call when event occurs
 * @returns Service instance for chaining
 */
on(event: string, listener: Function): this;

/**
 * Remove event listener
 * @param event - Event name
 * @param listener - Specific listener to remove (optional)
 * @returns Service instance for chaining
 */
off(event: string, listener?: Function): this;

/**
 * Execute listener once then remove it
 * @param event - Event name
 * @param listener - Function to call once
 * @returns Service instance for chaining
 */
once(event: string, listener: Function): this;

/**
 * Remove all listeners for an event or all events
 * @param event - Event name (optional, removes all if not specified)
 * @returns Service instance for chaining
 */
removeAllListeners(event?: string): this;

Usage Examples:

const userService = app.service("users");

// Add listener
const userCreatedHandler = (user) => {
  console.log("User created:", user.name);
};

userService.on("created", userCreatedHandler);

// One-time listener
userService.once("created", (user) => {
  console.log("First user created:", user.name);
});

// Remove specific listener
userService.off("created", userCreatedHandler);

// Remove all listeners for an event
userService.removeAllListeners("created");

// Remove all listeners for all events
userService.removeAllListeners();

Custom Events

Services can emit and listen for custom events beyond standard service events.

/**
 * Emit custom event to server
 * @param event - Event name
 * @param args - Event arguments
 * @returns Service instance for chaining
 */
emit(event: string, ...args: any[]): this;

Usage Examples:

const chatService = app.service("chat");

// Listen for custom events from server
chatService.on("user-typing", (data) => {
  showTypingIndicator(data.userId, data.message);
});

chatService.on("user-stopped-typing", (data) => {
  hideTypingIndicator(data.userId);
});

// Emit custom events to server
chatService.emit("typing", { message: "Hello..." });
chatService.emit("stop-typing");

// Custom room events
chatService.on("room-joined", (data) => {
  console.log(`${data.user.name} joined room ${data.roomId}`);
});

chatService.emit("join-room", { roomId: "general" });

Connection Management

Access Socket.IO connection directly through the application.

interface Application {
  /** Socket.io client instance (available when using socketio transport) */
  io: Socket;
}

Usage Examples:

// Access Socket.IO connection directly
const socket = app.io;

// Listen to connection events
socket.on("connect", () => {
  console.log("Connected to server");
});

socket.on("disconnect", () => {
  console.log("Disconnected from server");
});

socket.on("reconnect", () => {
  console.log("Reconnected to server");
});

// Check connection status
if (socket.connected) {
  console.log("Socket is connected");
}

// Manual connection management
socket.connect();
socket.disconnect();

Service-Specific Namespacing

Socket services automatically handle event namespacing based on service paths.

Usage Examples:

// Services automatically namespace their events
const userService = app.service("users");        // Listens to 'users::created', 'users::updated', etc.
const messageService = app.service("messages");  // Listens to 'messages::created', 'messages::updated', etc.

// Events are automatically namespaced by service path
userService.on("created", (user) => {
  // This only receives 'users::created' events
  console.log("New user:", user);
});

messageService.on("created", (message) => {
  // This only receives 'messages::created' events  
  console.log("New message:", message);
});

Error Handling

Socket services handle real-time errors and connection issues.

Usage Examples:

import { errors } from "@feathersjs/client";

const userService = app.service("users");

// Handle service operation errors
try {
  const user = await userService.get(999);
} catch (error) {
  if (error instanceof errors.NotFound) {
    console.log("User not found");
  }
}

// Handle connection errors
app.io.on("connect_error", (error) => {
  console.error("Connection error:", error);
});

app.io.on("error", (error) => {
  console.error("Socket error:", error);
});

// Handle authentication errors in real-time
userService.on("error", (error) => {
  if (error.name === "NotAuthenticated") {
    // Redirect to login
    window.location.href = "/login";
  }
});

Timeout Configuration

Configure request timeouts for Socket.IO service calls.

Usage Examples:

// Configure transport with timeout
app.configure(socketio(socket, {
  timeout: 5000  // 5 second timeout for service calls
}));

// Per-request timeout (if supported)
const users = await userService.find({
  timeout: 10000  // 10 second timeout for this request
});

Type Definitions

interface Socket {
  connected: boolean;
  id: string;
  
  connect(): Socket;
  disconnect(): Socket;
  
  on(event: string, listener: Function): Socket;
  off(event: string, listener?: Function): Socket;
  emit(event: string, ...args: any[]): Socket;
  once(event: string, listener: Function): Socket;
  
  addListener(event: string, listener: Function): Socket;
  removeListener(event: string, listener: Function): Socket;
  removeAllListeners(event?: string): Socket;
  
  listeners(event: string): Function[];
  listenerCount(event: string): number;
}

interface RealTimeConnection extends TransportConnection {
  connected: boolean;
  socket: Socket;
}