@pluskode/client
v0.1.1
Published
Pluskode Universal Client SDK for Web - TypeScript/JavaScript client with HTTP, WebSocket, SSE, gRPC, MQTT, and Binary Stream support
Maintainers
Readme
@pluskode/client
Universal Pluskode Client SDK for Web (Browser and Node.js)
Complete TypeScript/JavaScript client for the Pluskode Backend Framework with support for HTTP, WebSocket, SSE, gRPC, MQTT, and Binary Streams.
Installation
npm install @pluskode/clientOr with yarn:
yarn add @pluskode/clientQuick Start
import { PluskodeClient } from '@pluskode/client';
const client = new PluskodeClient({
baseURL: 'http://localhost:3000'
});
// GET request
const users = await client.get('/api/users');
// POST request
const newUser = await client.post('/api/users', {
name: 'John',
email: '[email protected]'
});
// WebSocket subscription
client.subscribe('chat/room1', (data) => {
console.log('New message:', data);
});Features
- ✅ HTTP Methods - GET, POST, PUT, DELETE, PATCH
- ✅ WebSocket - Auto-reconnect, channel subscriptions
- ✅ Server-Sent Events (SSE) - EventSource with auto-reconnect
- ✅ gRPC - Unary RPC calls
- ✅ MQTT - Topic subscriptions and publishing
- ✅ Binary Streams - WebSocket binary data handling
- ✅ Authentication - Bearer and Basic auth
- ✅ Retry Logic - Exponential backoff
- ✅ Offline Queue - Queue requests when offline
- ✅ TypeScript - Full type definitions
- ✅ Error Handling - Comprehensive error handling
API Reference
Constructor
const client = new PluskodeClient({
baseURL: string, // Required: Base URL
timeout?: number, // Default: 30000ms
headers?: Record<string, string>, // Default headers
retries?: number, // Default: 3
retryDelay?: number, // Default: 1000ms
wsReconnectDelay?: number, // Default: 3000ms
wsMaxReconnectAttempts?: number, // Default: Infinity
});HTTP Methods
GET
const response = await client.get<T>('/api/users', {
params?: { key: 'value' },
headers?: { 'X-Custom': 'value' },
timeout?: 5000,
signal?: AbortSignal,
});POST
const response = await client.post<T>('/api/users', {
name: 'John',
email: '[email protected]'
}, {
headers?: { 'Content-Type': 'application/json' }
});PUT, PATCH, DELETE
await client.put('/api/users/123', { name: 'Jane' });
await client.patch('/api/users/123', { email: '[email protected]' });
await client.delete('/api/users/123');Authentication
// Bearer token
client.setAuth('Bearer', 'your-jwt-token');
// Basic auth
client.setAuth('Basic', btoa('username:password'));
// Clear auth
client.clearAuth();
// Set custom header
client.setHeader('X-API-Key', 'key-123');WebSocket
// Subscribe to channel
const unsubscribe = client.subscribe('chat/room1', (data) => {
console.log('Message:', data);
});
// Send message
client.send('chat/room1', { text: 'Hello!' });
// Unsubscribe
unsubscribe();
// Disconnect
client.disconnectWebSocket();Server-Sent Events (SSE)
// Subscribe to SSE stream
const unsubscribe = client.subscribeSSE('/events/stream', (event) => {
console.log('Event:', event.event, event.data);
});
// Close SSE connection
unsubscribe();
// or
client.closeSSE('/events/stream');gRPC
// Call gRPC unary RPC
const user = await client.rpc('UserService', 'GetUser', {
id: '123'
});
const data = await client.rpc('DataService', 'GetData', {
query: 'test'
});MQTT
// Subscribe to MQTT topic
const unsubscribe = client.subscribeMQTT('sensors/temperature',
(topic, message, qos) => {
console.log(`${topic}: ${message} (QoS: ${qos})`);
},
{ qos: 1 }
);
// Publish MQTT message
await client.publishMQTT('sensors/temperature', '25.5', {
qos: 1,
retain: false
});
// Unsubscribe
unsubscribe();Binary Streams
// Connect to binary stream
const close = await client.connectBinary('/custom-protocol', (data) => {
console.log('Received:', data.byteLength, 'bytes');
// Process ArrayBuffer
});
// Close connection
close();Error Handling
try {
const data = await client.get('/api/data');
console.log('Success:', data.data);
} catch (error: any) {
console.error('Request failed:', error.message);
}
// With AbortController
const controller = new AbortController();
setTimeout(() => controller.abort(), 5000);
try {
const data = await client.get('/api/slow', {
signal: controller.signal
});
} catch (error: any) {
if (error.name === 'AbortError') {
console.log('Request aborted');
}
}Cleanup
// Cleanup all connections
client.destroy();Examples
React Example
import { useEffect, useState } from 'react';
import { PluskodeClient } from '@pluskode/client';
const client = new PluskodeClient({
baseURL: 'http://localhost:3000'
});
function UsersList() {
const [users, setUsers] = useState([]);
useEffect(() => {
client.get('/api/users')
.then(res => setUsers(res.data))
.catch(err => console.error(err));
}, []);
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}Vue Example
<template>
<div>
<ul>
<li v-for="user in users" :key="user.id">
{{ user.name }}
</li>
</ul>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { PluskodeClient } from '@pluskode/client';
const client = new PluskodeClient({
baseURL: 'http://localhost:3000'
});
const users = ref([]);
onMounted(async () => {
try {
const res = await client.get('/api/users');
users.value = res.data;
} catch (error) {
console.error(error);
}
});
</script>Node.js Example
import { PluskodeClient } from '@pluskode/client';
const client = new PluskodeClient({
baseURL: 'http://localhost:3000'
});
async function main() {
// HTTP
const users = await client.get('/api/users');
console.log('Users:', users.data);
// WebSocket
client.subscribe('notifications', (data) => {
console.log('Notification:', data);
});
// gRPC
const result = await client.rpc('Service', 'Method', { data: 'test' });
console.log('Result:', result);
}
main();TypeScript Support
Full TypeScript definitions are included. Import types as needed:
import {
PluskodeClient,
PluskodeClientOptions,
RequestOptions,
Response,
SSEEvent,
WebSocketMessage,
GRPCOptions,
MQTTOptions,
} from '@pluskode/client';Browser Support
- Chrome/Edge: Latest 2 versions
- Firefox: Latest 2 versions
- Safari: Latest 2 versions
- Node.js: 16+
License
MIT
