Skip to content

Commit 1f1e7b8

Browse files
committed
Update README and improve WebSocket functionality
- Streamlined the library to focus solely on WebSocket utilities, removing any DOM-related code. - Added support for custom WebSocket implementations via the new WebSocketImpl option. - Enhanced error handling and logging capabilities. - Updated usage examples in the README to reflect the latest API changes. - Documented breaking changes and improvements in the README.
1 parent b14e574 commit 1f1e7b8

11 files changed

+294
-357
lines changed

README.md

+17-115
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
1-
Nostr Websocket Utils
1+
# Nostr Websocket Utils
22

33
[![npm version](https://img.shields.io/npm/v/nostr-websocket-utils.svg)](https://www.npmjs.com/package/nostr-websocket-utils)
44
[![License](https://img.shields.io/npm/l/nostr-websocket-utils.svg)](https://github.com/HumanjavaEnterprises/nostr-websocket-utils/blob/main/LICENSE)
55
[![Build Status](https://github.com/HumanjavaEnterprises/nostr-websocket-utils/workflows/CI/badge.svg)](https://github.com/HumanjavaEnterprises/nostr-websocket-utils/actions)
66
[![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org)
77
[![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg)](https://github.com/prettier/prettier)
88

9-
A TypeScript library providing WebSocket utilities for Nostr applications, with robust connection handling, automatic reconnection, and channel-based messaging.
9+
A TypeScript library providing WebSocket utilities for Nostr applications, focusing on robust connection handling, automatic reconnection, and channel-based messaging. This library has been streamlined to remove any DOM-related code, enhancing performance and maintainability.
1010

1111
## Features
1212

@@ -25,12 +25,13 @@ A TypeScript library providing WebSocket utilities for Nostr applications, with
2525
npm install nostr-websocket-utils
2626
```
2727

28-
## Breaking Changes in v0.2.1
28+
## Breaking Changes in v0.2.2
2929

30-
- Added UUID support for message tracking and correlation
31-
- Fixed WebSocket mock implementation in tests
32-
- Improved TypeScript type safety across the codebase
33-
- Enhanced error handling for WebSocket connections
30+
- Removed all DOM-related code to focus solely on WebSocket functionality.
31+
- Added UUID support for message tracking and correlation.
32+
- Introduced a new `WebSocketImpl` option for custom WebSocket implementations.
33+
- Improved TypeScript type safety across the codebase.
34+
- Enhanced error handling for WebSocket connections.
3435

3536
## Usage
3637

@@ -52,79 +53,19 @@ const logger = winston.createLogger({
5253
transports: [new winston.transports.Console()]
5354
});
5455

55-
// Initialize WebSocket server with required handlers
56-
const wss = new NostrWSServer(server, {
57-
heartbeatInterval: 30000,
56+
// Initialize the WebSocket server with custom WebSocket implementation
57+
const wsServer = new NostrWSServer(server, {
5858
logger,
5959
handlers: {
60-
// Required message handler
6160
message: async (ws, message) => {
6261
logger.info('Received message:', message);
63-
64-
// Example: Handle different message types
65-
switch (message.type) {
66-
case 'subscribe':
67-
// Handle subscription
68-
break;
69-
case 'event':
70-
// Broadcast to specific channel
71-
wss.broadcastToChannel('my-channel', {
72-
type: 'event',
73-
data: { content: 'Hello channel!' }
74-
});
75-
break;
76-
}
62+
// Handle message
7763
},
78-
// Optional error handler
7964
error: (ws, error) => {
8065
logger.error('WebSocket error:', error);
8166
},
82-
// Optional close handler
8367
close: (ws) => {
84-
logger.info('Client disconnected');
85-
}
86-
}
87-
});
88-
89-
server.listen(3000);
90-
```
91-
92-
### Server Example with UUID
93-
94-
```typescript
95-
import express from 'express';
96-
import { createServer } from 'http';
97-
import { NostrWSServer } from 'nostr-websocket-utils';
98-
import winston from 'winston';
99-
100-
const app = express();
101-
const server = createServer(app);
102-
103-
// Create a logger
104-
const logger = winston.createLogger({
105-
level: 'info',
106-
format: winston.format.json(),
107-
transports: [new winston.transports.Console()]
108-
});
109-
110-
// Initialize the WebSocket server with UUID support
111-
const wsServer = new NostrWSServer({
112-
server,
113-
logger,
114-
messageHandler: async (message, client) => {
115-
// message.uuid will contain a unique identifier for the message
116-
logger.info(`Received message with UUID: ${message.uuid}`);
117-
118-
// Handle the message based on type
119-
switch (message.type) {
120-
case 'subscribe':
121-
// Handle subscription
122-
break;
123-
case 'event':
124-
// Handle event
125-
break;
126-
default:
127-
// Handle unknown message type
68+
logger.info('Connection closed');
12869
}
12970
}
13071
});
@@ -138,63 +79,22 @@ server.listen(3000);
13879
import { NostrWSClient } from 'nostr-websocket-utils';
13980
import winston from 'winston';
14081

141-
// Create a logger
14282
const logger = winston.createLogger({
14383
level: 'info',
14484
format: winston.format.json(),
14585
transports: [new winston.transports.Console()]
14686
});
14787

148-
const client = new NostrWSClient('wss://your-server.com', {
149-
heartbeatInterval: 30000,
150-
reconnectInterval: 5000,
151-
maxReconnectAttempts: 5,
152-
logger,
153-
handlers: {
154-
message: async (ws, message) => {
155-
logger.info('Received message:', message);
156-
// Handle message
157-
},
158-
error: (ws, error) => {
159-
logger.error('Connection error:', error);
160-
},
161-
close: (ws) => {
162-
logger.info('Connection closed');
163-
}
164-
}
165-
});
166-
167-
// Listen to events
168-
client.on('connect', () => {
169-
logger.info('Connected!');
170-
client.subscribe('my-channel');
171-
});
172-
173-
client.connect();
174-
```
175-
176-
### Client Example with UUID
177-
178-
```typescript
179-
import { NostrWSClient } from 'nostr-websocket-utils';
180-
18188
const client = new NostrWSClient('ws://localhost:3000', {
182-
logger: console
89+
logger,
90+
WebSocketImpl: CustomWebSocketImplementation // Optional custom WebSocket implementation
18391
});
18492

18593
client.on('message', (message) => {
186-
// Access the UUID of the received message
187-
console.log(`Received message with UUID: ${message.uuid}`);
94+
console.log('Received message:', message);
18895
});
18996

190-
// Connect to the server
19197
client.connect();
192-
193-
// Send a message (UUID will be automatically generated)
194-
client.send({
195-
type: 'event',
196-
data: { content: 'Hello, World!' }
197-
});
19898
```
19999

200100
## Interface Reference
@@ -220,6 +120,8 @@ interface NostrWSOptions {
220120
// Optional close handler
221121
close?: (ws: WebSocket) => void;
222122
};
123+
// Optional custom WebSocket implementation
124+
WebSocketImpl?: WebSocketImpl;
223125
}
224126
```
225127

package-lock.json

+6-6
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@
4343
"nostr-tools": "^2.1.4"
4444
},
4545
"devDependencies": {
46-
"@types/jest": "^29.5.11",
46+
"@types/jest": "^29.5.14",
4747
"@types/node": "^20.11.0",
4848
"@types/ws": "^8.5.10",
4949
"@typescript-eslint/eslint-plugin": "^6.18.1",

src/__mocks__/extendedWsMock.ts

+8-8
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ const extendedMockWebSocket = {
1212
OPEN: 1,
1313
CLOSING: 2,
1414
CLOSED: 3,
15-
on(event: string, listener: (...args: unknown[]) => void) {
15+
on(_event: string, _listener: (...args: unknown[]) => void) {
1616
return this;
1717
},
1818
send: jest.fn(),
@@ -22,13 +22,13 @@ const extendedMockWebSocket = {
2222
terminate: jest.fn(),
2323
removeAllListeners: jest.fn(),
2424
removeListener: jest.fn(),
25-
addEventListener: jest.fn(),
26-
removeEventListener: jest.fn(),
27-
emit: jest.fn(),
28-
addListener: jest.fn(),
29-
once: jest.fn(),
30-
prependListener: jest.fn(),
31-
prependOnceListener: jest.fn(),
25+
addEventListener: jest.fn((_event: string, _listener: (..._args: unknown[]) => void) => {}),
26+
removeEventListener: jest.fn((_event: string, _listener: (..._args: unknown[]) => void) => {}),
27+
emit: jest.fn((_event: string, ..._args: unknown[]) => {}),
28+
addListener: jest.fn((_event: string, _listener: (..._args: unknown[]) => void) => {}),
29+
once: jest.fn((_event: string, _listener: (..._args: unknown[]) => void) => {}),
30+
prependListener: jest.fn((_event: string, _listener: (..._args: unknown[]) => void) => {}),
31+
prependOnceListener: jest.fn((_event: string, _listener: (..._args: unknown[]) => void) => {}),
3232
eventNames: jest.fn(),
3333
listenerCount: jest.fn(),
3434
// Additional methods for extended behavior

0 commit comments

Comments
 (0)