feat(TypedSocket): Add SmartServe integration to TypedSocket, support SmartServe connections and tagging; update dependencies and docs; remove GitLab CI config
This commit is contained in:
349
readme.md
349
readme.md
@@ -1,159 +1,312 @@
|
||||
# @api.global/typedsocket
|
||||
a typedrequest extension supporting websockets
|
||||
|
||||
A TypeScript library for creating typed WebSocket connections with bi-directional communication support. Extends `@api.global/typedrequest` to bring type-safe request/response patterns to WebSocket connections.
|
||||
|
||||
## Issue Reporting and Security
|
||||
|
||||
For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://community.foss.global/). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/](https://code.foss.global/) account to submit Pull Requests directly.
|
||||
|
||||
## Features
|
||||
|
||||
- 🔒 **Full Type Safety** - Leverages TypeScript for compile-time checking of all request/response payloads
|
||||
- 🔄 **Bi-directional Communication** - Both server and client can initiate requests
|
||||
- 🔌 **Auto-reconnect** - Client automatically reconnects on connection loss
|
||||
- 🏷️ **Connection Tagging** - Tag and filter connections for targeted messaging
|
||||
- 🌐 **Browser Compatible** - Works in both Node.js and browser environments
|
||||
- 🔗 **SmartExpress Integration** - Optional integration with existing SmartExpress servers
|
||||
- 🚀 **SmartServe Integration** - Native support for SmartServe's WebSocket handling
|
||||
|
||||
## Install
|
||||
To install `@api.global/typedsocket` in your project, run the following command using npm:
|
||||
|
||||
```bash
|
||||
npm install @api.global/typedsocket --save
|
||||
npm install @api.global/typedsocket
|
||||
```
|
||||
|
||||
For Yarn users:
|
||||
Or with pnpm:
|
||||
|
||||
```bash
|
||||
yarn add @api.global/typedsocket
|
||||
pnpm 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.
|
||||
### Prerequisites
|
||||
|
||||
### Getting Started
|
||||
- TypeScript project setup
|
||||
- Basic understanding of async/await patterns
|
||||
- Familiarity with `@api.global/typedrequest` concepts
|
||||
|
||||
#### Prerequisites
|
||||
### Define Your Request Interface
|
||||
|
||||
Before diving into examples, ensure you have the following:
|
||||
First, define the typed request interface that both client and server will use:
|
||||
|
||||
- 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.
|
||||
```typescript
|
||||
import * as typedrequestInterfaces from '@api.global/typedrequest-interfaces';
|
||||
|
||||
#### Initialization
|
||||
interface IGreetingRequest extends typedrequestInterfaces.implementsTR<
|
||||
typedrequestInterfaces.ITypedRequest,
|
||||
IGreetingRequest
|
||||
> {
|
||||
method: 'greet';
|
||||
request: {
|
||||
name: string;
|
||||
};
|
||||
response: {
|
||||
message: string;
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
First, let's import the required modules and initialize our server and client instances.
|
||||
### Server Setup
|
||||
|
||||
**Server Side:**
|
||||
|
||||
Within your server-side code, import and set up `TypedSocket` to create a websocket server.
|
||||
Create a WebSocket server that handles typed requests:
|
||||
|
||||
```typescript
|
||||
import { TypedSocket } from '@api.global/typedsocket';
|
||||
import * as typedrequest from '@api.global/typedrequest';
|
||||
|
||||
// Initialize your TypedRouter
|
||||
// Create the router and add handlers
|
||||
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) => {
|
||||
typedRouter.addTypedHandler<IGreetingRequest>(
|
||||
new typedrequest.TypedHandler('greet', async (requestData) => {
|
||||
return {
|
||||
reply: `Server received: ${requestData.message}`,
|
||||
message: `Hello, ${requestData.name}! 👋`,
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
// Start the TypedSocket server (defaults to port 3000)
|
||||
const server = await TypedSocket.createServer(typedRouter);
|
||||
```
|
||||
|
||||
### Sending Requests from the Client
|
||||
#### Integration with SmartExpress
|
||||
|
||||
Use the client instance to send a request to the server and await a response.
|
||||
If you have an existing SmartExpress server, you can attach TypedSocket to it:
|
||||
|
||||
```typescript
|
||||
const exampleRequest = client.createTypedRequest<ExampleRequest>('exampleMethod');
|
||||
const response = await exampleRequest.fire({
|
||||
message: 'Hello from client!',
|
||||
import { TypedSocket } from '@api.global/typedsocket';
|
||||
import * as smartexpress from '@push.rocks/smartexpress';
|
||||
|
||||
const smartExpressServer = new smartexpress.Server({ port: 8080 });
|
||||
await smartExpressServer.start();
|
||||
|
||||
const server = await TypedSocket.createServer(typedRouter, smartExpressServer);
|
||||
```
|
||||
|
||||
#### Integration with SmartServe
|
||||
|
||||
For SmartServe-based applications, use `fromSmartServe()` for native integration:
|
||||
|
||||
```typescript
|
||||
import { TypedSocket } from '@api.global/typedsocket';
|
||||
import { SmartServe } from '@push.rocks/smartserve';
|
||||
import * as typedrequest from '@api.global/typedrequest';
|
||||
|
||||
const typedRouter = new typedrequest.TypedRouter();
|
||||
|
||||
// Add handlers for client-to-server requests
|
||||
typedRouter.addTypedHandler<IGreetingRequest>(
|
||||
new typedrequest.TypedHandler('greet', async (requestData) => {
|
||||
return { message: `Hello, ${requestData.name}!` };
|
||||
})
|
||||
);
|
||||
|
||||
// Create SmartServe with typedRouter in websocket options
|
||||
const smartServe = new SmartServe({
|
||||
port: 3000,
|
||||
websocket: {
|
||||
typedRouter,
|
||||
onConnectionOpen: (peer) => {
|
||||
// Tag connections for later filtering
|
||||
peer.tags.add('client');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
console.log(response.reply); // "Server received: Hello from client!"
|
||||
```
|
||||
await smartServe.start();
|
||||
|
||||
### Advanced Usage
|
||||
// Create TypedSocket bound to SmartServe
|
||||
const typedSocket = TypedSocket.fromSmartServe(smartServe, typedRouter);
|
||||
|
||||
#### 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',
|
||||
});
|
||||
// Push notifications to tagged clients
|
||||
const clients = await typedSocket.findAllTargetConnectionsByTag('client');
|
||||
for (const client of clients) {
|
||||
const request = typedSocket.createTypedRequest<INotifyRequest>('notify', client);
|
||||
await request.fire({ message: 'Hello from server!' });
|
||||
}
|
||||
```
|
||||
|
||||
#### Handling Reconnections
|
||||
> **Note:** When using SmartServe, the WebSocket transport is managed by SmartServe. TypedSocket acts as a convenience layer for finding connections and sending server-initiated requests.
|
||||
|
||||
`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.
|
||||
### Client Setup
|
||||
|
||||
### Conclusion
|
||||
Connect to the WebSocket server from a client:
|
||||
|
||||
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.
|
||||
```typescript
|
||||
import { TypedSocket } from '@api.global/typedsocket';
|
||||
import * as typedrequest from '@api.global/typedrequest';
|
||||
|
||||
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.
|
||||
// Create a router for handling server-initiated requests (if needed)
|
||||
const clientRouter = new typedrequest.TypedRouter();
|
||||
|
||||
// Connect to the server
|
||||
const client = await TypedSocket.createClient(
|
||||
clientRouter,
|
||||
'http://localhost:3000'
|
||||
);
|
||||
```
|
||||
|
||||
#### Using Window Location (Browser)
|
||||
|
||||
In browser environments, you can automatically use the current page's origin:
|
||||
|
||||
```typescript
|
||||
const client = await TypedSocket.createClient(
|
||||
clientRouter,
|
||||
TypedSocket.useWindowLocationOriginUrl()
|
||||
);
|
||||
```
|
||||
|
||||
### Sending Requests
|
||||
|
||||
#### Client to Server
|
||||
|
||||
```typescript
|
||||
const request = client.createTypedRequest<IGreetingRequest>('greet');
|
||||
const response = await request.fire({
|
||||
name: 'World',
|
||||
});
|
||||
|
||||
console.log(response.message); // "Hello, World! 👋"
|
||||
```
|
||||
|
||||
#### Server to Client
|
||||
|
||||
The server can also initiate requests to connected clients:
|
||||
|
||||
```typescript
|
||||
// When only one client is connected, it's automatically selected
|
||||
const request = server.createTypedRequest<IGreetingRequest>('greet');
|
||||
const response = await request.fire({
|
||||
name: 'Client',
|
||||
});
|
||||
|
||||
// For multiple clients, specify the target connection
|
||||
const connection = await server.findTargetConnection(async (conn) => {
|
||||
// Your filter logic here
|
||||
return true;
|
||||
});
|
||||
const targetedRequest = server.createTypedRequest<IGreetingRequest>('greet', connection);
|
||||
```
|
||||
|
||||
### Connection Tagging
|
||||
|
||||
Tag connections for organized, targeted communication:
|
||||
|
||||
```typescript
|
||||
// Client side: add a tag
|
||||
interface IUserTag extends typedrequestInterfaces.ITag {
|
||||
name: 'userRole';
|
||||
payload: 'admin' | 'user' | 'guest';
|
||||
}
|
||||
|
||||
client.addTag<IUserTag>('userRole', 'admin');
|
||||
```
|
||||
|
||||
```typescript
|
||||
// Server side: find connections by tag
|
||||
const adminConnections = await server.findAllTargetConnectionsByTag<IUserTag>(
|
||||
'userRole',
|
||||
'admin'
|
||||
);
|
||||
|
||||
// Send to all admins
|
||||
for (const conn of adminConnections) {
|
||||
const request = server.createTypedRequest<INotificationRequest>('notify', conn);
|
||||
await request.fire({ message: 'Admin notification' });
|
||||
}
|
||||
|
||||
// Find a single connection
|
||||
const firstAdmin = await server.findTargetConnectionByTag<IUserTag>('userRole', 'admin');
|
||||
```
|
||||
|
||||
### Event Handling
|
||||
|
||||
Subscribe to connection status events:
|
||||
|
||||
```typescript
|
||||
client.eventSubject.subscribe((status) => {
|
||||
console.log('Connection status:', status);
|
||||
});
|
||||
|
||||
server.eventSubject.subscribe((status) => {
|
||||
console.log('Server connection event:', status);
|
||||
});
|
||||
```
|
||||
|
||||
### Cleanup
|
||||
|
||||
Properly close connections when done:
|
||||
|
||||
```typescript
|
||||
// Client
|
||||
await client.stop();
|
||||
|
||||
// Server
|
||||
await server.stop();
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
### TypedSocket
|
||||
|
||||
#### Static Methods
|
||||
|
||||
| Method | Description |
|
||||
|--------|-------------|
|
||||
| `createServer(router, smartExpressServer?)` | Creates a WebSocket server. Optionally attach to an existing SmartExpress server. |
|
||||
| `createClient(router, serverUrl, alias?)` | Creates a WebSocket client that connects to the specified server URL. |
|
||||
| `fromSmartServe(smartServe, router)` | Creates a TypedSocket bound to an existing SmartServe instance. |
|
||||
| `useWindowLocationOriginUrl()` | Returns the current window location origin (browser only). |
|
||||
|
||||
#### Instance Properties
|
||||
|
||||
| Property | Description |
|
||||
|----------|-------------|
|
||||
| `side` | Whether this instance is a `'server'` or `'client'`. |
|
||||
| `typedrouter` | The TypedRouter instance handling requests. |
|
||||
| `eventSubject` | RxJS Subject for connection status events. |
|
||||
|
||||
#### Instance Methods
|
||||
|
||||
| Method | Description |
|
||||
|--------|-------------|
|
||||
| `createTypedRequest(method, targetConnection?)` | Creates a typed request for the specified method. |
|
||||
| `addTag(name, payload)` | Adds a tag to the client connection (client-side only). |
|
||||
| `findAllTargetConnections(filterFn)` | Finds all connections matching the filter (server-side only). |
|
||||
| `findTargetConnection(filterFn)` | Finds the first connection matching the filter (server-side only). |
|
||||
| `findAllTargetConnectionsByTag(key, payload?)` | Finds all connections with the specified tag. |
|
||||
| `findTargetConnectionByTag(key, payload?)` | Finds the first connection with the specified tag. |
|
||||
| `stop()` | Closes the WebSocket connection. |
|
||||
|
||||
## 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.
|
||||
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE](./LICENSE) file.
|
||||
|
||||
**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.
|
||||
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 or third parties, 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 or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
|
||||
|
||||
### Company Information
|
||||
|
||||
Task Venture Capital GmbH
|
||||
Registered at District court Bremen HRB 35230 HB, Germany
|
||||
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.
|
||||
For any legal inquiries or 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.
|
||||
|
||||
Reference in New Issue
Block a user