PeerService API Reference
The PeerService is the main class for managing peer-to-peer connections, contacts, and messages.
Table of Contentsβ
Constructorβ
new PeerService(config)β
Creates a new PeerService instance.
new PeerService(config: PeerServiceConfig)
Parametersβ
| Parameter | Type | Required | Description |
|---|---|---|---|
config | PeerServiceConfig | Yes | Configuration object for the peer service |
PeerServiceConfigβ
interface PeerServiceConfig {
vaultysId?: VaultysId; // Identity for this peer
storageProvider?: StorageProvider; // Storage backend
eventBus?: EventBus; // Event bus for integration
relay?: PeerJSConfig; // PeerJS configuration
defaultPeerConfig?: PeerConfig; // Default peer configuration
debug?: boolean; // Enable debug logging
}
Exampleβ
const peerService = new PeerService({
vaultysId: await VaultysId.generatePerson(),
storageProvider: new BrowserStorageProvider(),
debug: true,
relay: {
host: 'peerjs.92k.de',
port: 443,
secure: true
}
});
Methodsβ
Core Methodsβ
initialize()β
Initializes the peer service and connects to the relay.
async initialize(): Promise<void>
Returns: Promise that resolves when initialization is complete
Example:
await peerService.initialize();
console.log('Peer service initialized');
disconnect()β
Disconnects from all peers and the relay.
async disconnect(): Promise<void>
Example:
await peerService.disconnect();
getDid()β
Gets the DID (Decentralized Identifier) of this peer.
async getDid(): Promise<string>
Returns: The peer's DID
Example:
const myDid = await peerService.getDid();
console.log('My DID:', myDid);
Contact Managementβ
addContact(did, metadata?)β
Adds a new contact or updates an existing one.
async addContact(
did: string,
metadata?: PeerMetadata
): Promise<Peer>
Parameters:
did- The DID of the contact to addmetadata- Optional metadata for the contact
Returns: The created or updated Peer object
Example:
const contact = await peerService.addContact(
'did:vaultys:123456',
{
nickname: 'Alice',
accepted: true
}
);
removeContact(did)β
Removes a contact and all associated data.
async removeContact(did: string): Promise<void>
Example:
await peerService.removeContact('did:vaultys:123456');
getContacts()β
Gets all contacts.
getContacts(): Peer[]
Returns: Array of Peer objects
Example:
const contacts = peerService.getContacts();
contacts.forEach(contact => {
console.log(contact.did, contact.metadata?.nickname);
});
getContact(did)β
Gets a specific contact by DID.
getContact(did: string): Peer | undefined
Returns: Peer object or undefined if not found
Example:
const contact = peerService.getContact('did:vaultys:123456');
if (contact) {
console.log('Found:', contact.metadata?.nickname);
}
Messagingβ
sendMessage(toDid, content, type?, fileData?, metadata?)β
Sends a message to a peer.
async sendMessage(
toDid: string,
content: string,
type?: MessageType,
fileData?: FileData | null,
metadata?: any
): Promise<Message>
Parameters:
toDid- DID of the recipientcontent- Message contenttype- Message type ('text', 'file', 'room', 'system')fileData- File data for file messagesmetadata- Additional metadata
Returns: The sent Message object
Example:
// Send text message
const message = await peerService.sendMessage(
'did:vaultys:123456',
'Hello, Alice!'
);
// Send file
const fileMessage = await peerService.sendMessage(
'did:vaultys:123456',
'Sending document',
'file',
{
name: 'document.pdf',
size: 1024000,
type: 'application/pdf',
data: arrayBuffer
}
);
loadMessages(did, limit?, offset?)β
Loads message history with a contact.
async loadMessages(
did: string,
limit?: number,
offset?: number
): Promise<Message[]>
Parameters:
did- DID of the contactlimit- Maximum number of messages to load (default: 50)offset- Number of messages to skip
Returns: Array of Message objects
Example:
// Load last 20 messages
const messages = await peerService.loadMessages(
'did:vaultys:123456',
20
);
// Load with pagination
const olderMessages = await peerService.loadMessages(
'did:vaultys:123456',
20,
20
);
deleteMessage(messageId, did)β
Deletes a message from storage.
async deleteMessage(
messageId: string,
did: string
): Promise<void>
Example:
await peerService.deleteMessage('msg-123', 'did:vaultys:123456');
Group Managementβ
createGroup(name, description?)β
Creates a new group.
async createGroup(
name: string,
description?: string
): Promise<Group>
Returns: The created Group object
Example:
const group = await peerService.createGroup(
'Project Team',
'Team collaboration group'
);
addPeerToGroup(peerDid, groupId)β
Adds a peer to a group.
async addPeerToGroup(
peerDid: string,
groupId: string
): Promise<void>
Example:
await peerService.addPeerToGroup(
'did:vaultys:123456',
'group-001'
);
getGroups()β
Gets all groups.
getGroups(): Group[]
Returns: Array of Group objects
Example:
const groups = peerService.getGroups();
groups.forEach(group => {
console.log(group.name, group.peerDids.length);
});
Connection Managementβ
connectToPeer(did)β
Manually connects to a peer.
async connectToPeer(did: string): Promise<VaultysPeer>
Returns: VaultysPeer connection object
Example:
try {
const connection = await peerService.connectToPeer('did:vaultys:123456');
console.log('Connected to peer');
} catch (error) {
console.error('Connection failed:', error);
}
isConnected(did)β
Checks if connected to a peer.
isConnected(did: string): boolean
Returns: true if connected, false otherwise
Example:
if (peerService.isConnected('did:vaultys:123456')) {
console.log('Peer is connected');
}
Eventsβ
The PeerService extends EventEmitter and emits the following events:
Connection Eventsβ
relay-connectedβ
Emitted when connected to the relay.
peerService.on('relay-connected', (did) => {
console.log('Connected with DID:', did);
});
relay-disconnectedβ
Emitted when disconnected from the relay.
peerService.on('relay-disconnected', () => {
console.log('Disconnected from server');
});
relay-errorβ
Emitted when a PeerJS error occurs.
peerService.on('relay-error', (error) => {
console.error('PeerJS error:', error);
});
Peer Eventsβ
peer-statusβ
Emitted when a peer's connection status changes.
peerService.on('peer-status', (did, status) => {
console.log(`Peer ${did} is ${status}`);
// status: 'connecting' | 'connected' | 'disconnected' | 'error'
});
contact-onlineβ
Emitted when a contact comes online.
peerService.on('contact-online', (did) => {
console.log(`${did} is now online`);
});
contact-offlineβ
Emitted when a contact goes offline.
peerService.on('contact-offline', (did) => {
console.log(`${did} is now offline`);
});
Message Eventsβ
message-receivedβ
Emitted when a message is received.
peerService.on('message-received', (message) => {
console.log('New message:', message.content);
console.log('From:', message.from);
console.log('Type:', message.type);
if (message.fileData) {
console.log('File:', message.fileData.name);
}
});
message-sentβ
Emitted when a message is successfully sent.
peerService.on('message-sent', (message) => {
console.log('Message sent to:', message.to);
});
Error Eventsβ
errorβ
Emitted when an error occurs.
peerService.on('error', (error) => {
console.error('Service error:', error);
});
Typesβ
Messageβ
interface Message {
id: string;
from: string;
to: string;
content: string;
type: MessageType;
timestamp: number;
status?: MessageStatus;
fileData?: FileData;
metadata?: any;
}
MessageTypeβ
type MessageType = 'text' | 'file' | 'room' | 'system';
MessageStatusβ
type MessageStatus = 'pending' | 'sent' | 'delivered' | 'read' | 'error';
FileDataβ
interface FileData {
name: string;
size: number;
type: string;
data: ArrayBuffer;
url?: string;
}
Peerβ
interface Peer {
did: string;
metadata?: PeerMetadata;
isConnected: boolean;
lastSeen?: number;
connection?: VaultysPeer;
}
PeerMetadataβ
interface PeerMetadata {
nickname?: string;
avatar?: string;
accepted?: boolean;
blocked?: boolean;
[key: string]: any;
}
Groupβ
interface Group {
id: string;
name: string;
description?: string;
peerDids: string[];
created: number;
metadata?: any;
}
Examplesβ
Complete Example: Building a Chat Applicationβ
import {
PeerService,
BrowserStorageProvider
} from '@vaultys/peer-sdk';
import { VaultysId } from '@vaultys/id';
class ChatApp {
constructor() {
this.peerService = null;
this.myDid = null;
}
async initialize() {
// Create identity
const vaultysId = await VaultysId.generatePerson();
this.myDid = vaultysId.did;
// Set up peer service
this.peerService = new PeerService({
vaultysId,
storageProvider: new BrowserStorageProvider(),
debug: true
});
// Set up event handlers
this.setupEventHandlers();
// Initialize service
await this.peerService.initialize();
console.log('Chat app ready!');
console.log('Your DID:', this.myDid);
}
setupEventHandlers() {
// Connection events
this.peerService.on('relay-connected', () => {
this.updateStatus('Connected');
});
this.peerService.on('relay-disconnected', () => {
this.updateStatus('Disconnected');
});
// Message events
this.peerService.on('message-received', (message) => {
this.displayMessage(message);
// Send read receipt
if (message.type === 'text') {
this.sendReceipt(message);
}
});
// Contact events
this.peerService.on('contact-online', (did) => {
this.updateContactStatus(did, 'online');
});
this.peerService.on('contact-offline', (did) => {
this.updateContactStatus(did, 'offline');
});
// Error handling
this.peerService.on('error', (error) => {
console.error('Chat error:', error);
this.showError(error.message);
});
}
async addContact(did, nickname) {
try {
const contact = await this.peerService.addContact(did, {
nickname: nickname,
accepted: true
});
console.log('Contact added:', contact);
return contact;
} catch (error) {
console.error('Failed to add contact:', error);
throw error;
}
}
async sendMessage(toDid, content) {
try {
const message = await this.peerService.sendMessage(
toDid,
content,
'text'
);
this.displayMessage(message);
return message;
} catch (error) {
console.error('Failed to send message:', error);
throw error;
}
}
async sendFile(toDid, file) {
try {
const arrayBuffer = await file.arrayBuffer();
const message = await this.peerService.sendMessage(
toDid,
`Sent file: ${file.name}`,
'file',
{
name: file.name,
size: file.size,
type: file.type,
data: arrayBuffer
}
);
return message;
} catch (error) {
console.error('Failed to send file:', error);
throw error;
}
}
async loadChatHistory(did) {
const messages = await this.peerService.loadMessages(did, 50);
messages.forEach(msg => this.displayMessage(msg));
return messages;
}
// UI update methods (implement based on your UI framework)
updateStatus(status) {
console.log('Status:', status);
}
displayMessage(message) {
console.log('Message:', message);
}
updateContactStatus(did, status) {
console.log(`Contact ${did} is ${status}`);
}
showError(error) {
console.error('Error:', error);
}
sendReceipt(message) {
// Implement read receipt logic
}
async cleanup() {
if (this.peerService) {
await this.peerService.disconnect();
}
}
}
// Usage
const app = new ChatApp();
app.initialize().then(() => {
console.log('Chat app is running!');
});
Best Practicesβ
- Always Initialize: Call
initialize()before using any other methods - Handle Errors: Subscribe to the 'error' event and handle failures gracefully
- Clean Disconnection: Call
disconnect()when shutting down - Message Validation: Validate message content before sending
- Connection Management: Monitor peer-status events for connection health
- Storage Cleanup: Periodically clean old messages if storage is limited
- Retry Logic: Implement retry for failed message sends
- Rate Limiting: Implement rate limiting for message sending in production