---
title: "@api.global/typedsocket"
---
# @api.global/typedsocket
a typedrequest extension supporting websockets

## Install
To install `@api.global/typedsocket` in your project, run the following command using npm:

```bash
npm install @api.global/typedsocket --save
```

For Yarn users:

```bash
yarn add @api.global/typedsocket
```

## Usage

To utilize `@api.global/typedsocket` effectively, let's explore how to integrate it into a project with TypeScript. This guide provides comprehensive usage scenarios, highlighting all features of the module. `@api.global/typedsocket` extends the capabilities of `typedrequest` by integrating websocket support, allowing for real-time, bidirectional communication between a client and server.

### Getting Started

#### Prerequisites

Before diving into examples, ensure you have the following:

- A basic understanding of TypeScript and Node.js.
- An existing project set up with TypeScript.
- `@api.global/typedrequest` and its dependencies installed in your project.

#### Initialization

First, let's import the required modules and initialize our server and client instances.

**Server Side:**

Within your server-side code, import and set up `TypedSocket` to create a websocket server.

```typescript
import { TypedSocket } from '@api.global/typedsocket';
import * as typedrequest from '@api.global/typedrequest';

// Initialize your TypedRouter
const typedRouter = new typedrequest.TypedRouter();

// Create the TypedSocket server
const server = await TypedSocket.createServer(typedRouter);

// Optionally, you can provide a smartexpressServerArg if you have an existing SmartExpress server
```

**Client Side:**

On the client side, initialize `TypedSocket` to connect to the websocket server.

```typescript
import { TypedSocket } from '@api.global/typedsocket';

// Assuming server is at http://localhost:3000
const client = await TypedSocket.createClient(typedRouter, 'http://localhost:3000');
```

### Defining Typed Requests

`@api.global/typedsocket` leverages `typedrequest` for type-safe requests and responses. Here's how you can define and handle typed requests:

**Defining a Typed Request Interface:**

Define an interface for the request and its corresponding response.

```typescript
interface ExampleRequest extends typedrequestInterfaces.ITypedRequest {
  method: 'exampleMethod';
  request: {
    message: string;
  };
  response: {
    reply: string;
  };
}
```

**Handling Requests on the Server:**

Add a typed handler for the request in your `TypedRouter`.

```typescript
typedRouter.addTypedHandler<ExampleRequest>(
  new typedrequest.TypedHandler('exampleMethod', async (requestData) => {
    return {
      reply: `Server received: ${requestData.message}`,
    };
  })
);
```

### Sending Requests from the Client

Use the client instance to send a request to the server and await a response.

```typescript
const exampleRequest = client.createTypedRequest<ExampleRequest>('exampleMethod');
const response = await exampleRequest.fire({
  message: 'Hello from client!',
});

console.log(response.reply); // "Server received: Hello from client!"
```

### Advanced Usage

#### Tagging Connections

For more refined control, especially in scenarios with multiple clients, you can tag connections for targeted communication.

```typescript
// Add a tag to a client
client.addTag('role', 'admin');

// On the server, find connections with the tag
const adminConnections = await server.findAllTargetConnectionsByTag('role', 'admin');

// Send a message to all admin connections
for (const adminConnection of adminConnections) {
  const request = server.createTypedRequest<ExampleRequest>('exampleMethod', adminConnection);
  await request.fire({
    message: 'Message to admins',
  });
}
```

#### Handling Reconnections

`TypedSocket` automatically attempts to reconnect in the event of connection loss. Ensure your server and client logic accounts for reconnection, especially for maintaining state or re-subscribing to necessary events.

### Conclusion

Implementing `@api.global/typedsocket` provides a type-safe, real-time communication layer for your TypeScript applications, extending the functionality of `typedrequest` into the realm of websockets. This guide covered initialization, defining typed requests, sending requests, and advanced usage patterns like tagging connections and handling reconnections.

Integrating `@api.global/typedsocket` into your project harnesses the power of websockets with the benefits of type safety and structured request/response patterns, enabling more reliable and maintainable real-time applications.

## License and Legal Information

This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. 

**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.

### Trademarks

This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.

### Company Information

Task Venture Capital GmbH  
Registered at District court Bremen HRB 35230 HB, Germany

For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.

By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
