Skip to main content

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​

ParameterTypeRequiredDescription
configPeerServiceConfigYesConfiguration 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 add
  • metadata - 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 recipient
  • content - Message content
  • type - Message type ('text', 'file', 'room', 'system')
  • fileData - File data for file messages
  • metadata - 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 contact
  • limit - 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​

  1. Always Initialize: Call initialize() before using any other methods
  2. Handle Errors: Subscribe to the 'error' event and handle failures gracefully
  3. Clean Disconnection: Call disconnect() when shutting down
  4. Message Validation: Validate message content before sending
  5. Connection Management: Monitor peer-status events for connection health
  6. Storage Cleanup: Periodically clean old messages if storage is limited
  7. Retry Logic: Implement retry for failed message sends
  8. Rate Limiting: Implement rate limiting for message sending in production