@tryboy869/frontendraft
v0.1.1
Published
RAFT (Reactive API for Frontend Transformation) - Turn browsers into API servers. Inspired by CSOP.
Maintainers
Readme
🚀 FrontendRAFT
RAFT = Reactive API for Frontend Transformation
Turn browsers into API servers with zero infrastructure cost. FrontendRAFT extends REST with streaming, caching, batching, optimistic updates, and query capabilities.
Inspired by CSOP (Client-Side Orchestration Protocol)
📋 Table of Contents
🎯 What is RAFT?
RAFT is a protocol that transforms browsers into full-fledged API servers. It's REST++ - maintaining 100% REST compatibility while adding powerful new capabilities:
REST (What You Know)
- ✅ GET, POST, PUT, DELETE, PATCH
- ✅ Headers (Authorization, CORS)
- ✅ Status codes (200, 404, 500)
- ✅ JSON payloads
- ✅ JWT authentication
- ✅ Rate limiting
RAFT (What's New)
- 🌊 Streaming API - Real-time via async generators
- 💾 Smart Caching - Multi-strategy with TTL
- ⚡ Auto-Batching - Parallel request optimization
- 🚀 Optimistic Updates - Instant UI with rollback
- 🔍 Query Language - GraphQL-like data fetching
Result: RAFT = REST + Real-time + Performance + Offline-first + $0 infrastructure
✨ Features
1. Streaming API
for await (const message of raft.stream('channel', generator)) {
console.log(message);
}2. Smart Caching
const data = await raft.executeWithCache('key', fetcher, ttl);3. Auto-Batching
const results = await raft.batchExecute(requests);4. Optimistic Updates
await raft.optimisticUpdate(entity, optimisticData, actualRequest);5. Query Language
const filtered = raft.queryData(data, {
where: { age: { $gte: 25 } },
select: ['name', 'email'],
orderBy: ['-createdAt']
});📦 Installation
NPM
npm install @tryboy869/frontendraftYarn
yarn add @tryboy869/frontendraftCDN (Browser)
<script type="module">
import { FrontendRAFT } from 'https://cdn.jsdelivr.net/npm/@tryboy869/[email protected]/dist/index.js';
</script>🚀 Quick Start
Basic Setup
import { FrontendRAFT } from '@tryboy869/frontendraft';
// Create instance
const raft = new FrontendRAFT({
name: 'My API',
version: '1.0.0',
autoRegister: true
});
// Initialize
await raft.init();
// Define routes
raft.get('/hello', async (req) => {
return { message: 'Hello from RAFT!' };
});
raft.post('/users', async (req) => {
const user = req.body;
await raft.storage.save(`user:${user.id}`, user);
return { success: true, user };
});
// Handle requests
const response = await raft.handle({
method: 'GET',
path: '/hello'
});With Authentication
// Sign up
const { user, token } = await raft.auth.signup(
'[email protected]',
'password123',
{ plan: 'free', quota: 1000 }
);
// Login
const { user, token } = await raft.auth.login(
'[email protected]',
'password123'
);
// Protected route
raft.use(raft.auth.middleware());
raft.get('/profile', async (req) => {
return { user: req.user };
});🧠 Core Concepts
1. Storage Layer
Persistent storage using IndexedDB:
await raft.storage.save('key', data);
const data = await raft.storage.get('key');
await raft.storage.delete('key');
const keys = await raft.storage.list('prefix:');2. Compute Layer
Parallel computation with Web Workers:
const result = await raft.compute.execute(
(args) => args.numbers.reduce((a, b) => a + b, 0),
{ numbers: [1, 2, 3, 4, 5] }
);
const batchResults = await raft.compute.batch([
{ fn: task1, args: data1 },
{ fn: task2, args: data2 }
]);3. Cache Layer
Intelligent caching with multiple strategies:
raft.cache.set('key', value, ttl);
const value = raft.cache.get('key');
raft.cache.delete('key');
// Strategies: 'lru', 'lfu', 'fifo'
const stats = raft.cache.getStats();4. Router
Express-like routing:
raft.use(middleware);
raft.get('/path', handler);
raft.post('/path', handler);
raft.put('/path', handler);
raft.delete('/path', handler);
raft.patch('/path', handler);
// With parameters
raft.get('/users/:id', async (req) => {
const userId = req.params.id;
return { userId };
});5. P2P Layer
WebRTC peer-to-peer communication:
const peer = await raft.p2p.createPeer('peer-id');
await raft.p2p.createDataChannel('peer-id');
raft.p2p.send('peer-id', { message: 'Hello' });
raft.p2p.broadcast({ type: 'update', data: {...} });📚 API Reference
See RAFT_PROTOCOL.md for complete protocol specification.
Main Class: FrontendRAFT
Constructor
new FrontendRAFT(config)Config Options:
name(string, required) - API nameversion(string) - API versionautoRegister(boolean) - Auto-register on CDNauth(object) - Authentication configcache(object) - Cache configrateLimit(object) - Rate limiting config
Methods
init()
await raft.init()Initialize all components. Must be called before using the API.
HTTP Methods
raft.get(path, handler)
raft.post(path, handler)
raft.put(path, handler)
raft.delete(path, handler)
raft.patch(path, handler)Middleware
raft.use(middleware)Handle Request
await raft.handle(request)Streaming
for await (const msg of raft.stream(channel, generator, config)) {
// Process message
}Subscribe
const unsubscribe = raft.subscribe(channel, callback)Cache
await raft.executeWithCache(key, fetcher, ttl)Batch
await raft.batchExecute(requests)Optimistic Update
await raft.optimisticUpdate(entity, optimisticData, actualRequest, options)Query
raft.queryData(data, options)Stats
await raft.getStats()Destroy
await raft.destroy()💡 Examples
Complete Todo API
const raft = new FrontendRAFT({ name: 'Todo API' });
await raft.init();
// Create todo
raft.post('/todos', async (req) => {
const todo = {
id: Date.now(),
...req.body,
createdAt: Date.now()
};
await raft.storage.save(`todo:${todo.id}`, todo);
return { success: true, todo };
});
// Get all todos
raft.get('/todos', async (req) => {
const keys = await raft.storage.list('todo:');
const todos = [];
for (const key of keys) {
const todo = await raft.storage.get(key);
todos.push(todo);
}
return { todos };
});
// Update todo
raft.put('/todos/:id', async (req) => {
const todoId = req.params.id;
const updates = req.body;
let todo = await raft.storage.get(`todo:${todoId}`);
todo = { ...todo, ...updates, updatedAt: Date.now() };
await raft.storage.save(`todo:${todoId}`, todo);
return { success: true, todo };
});
// Delete todo
raft.delete('/todos/:id', async (req) => {
const todoId = req.params.id;
await raft.storage.delete(`todo:${todoId}`);
return { success: true };
});Real-time Notifications
// Start notification stream
raft.get('/notifications/stream', async (req) => {
const stream = raft.stream('notifications', async () => {
return {
type: 'notification',
message: 'New update available',
timestamp: Date.now()
};
}, { interval: 5000 });
return { stream: 'started' };
});
// Subscribe to notifications
const unsubscribe = raft.subscribe('notifications', (message) => {
console.log('Notification:', message);
});Optimistic UI Updates
const currentData = { name: 'John', email: '[email protected]' };
const result = await raft.optimisticUpdate(
'user-profile',
{ ...currentData, name: 'Jane' }, // Optimistic
async () => {
// Actual API call
return await fetch('/api/update', {
method: 'POST',
body: JSON.stringify({ name: 'Jane' })
});
},
{
originalData: currentData,
onOptimistic: (data) => updateUI(data),
onConfirm: (data) => console.log('Confirmed:', data),
onRollback: (data) => console.log('Rolled back:', data)
}
);🤝 Contributing
See CONTRIBUTING.md for guidelines.
📄 License
MIT License - see LICENSE
🙏 Credits
Created by: DAOUDA Abdoul Anzize (Nexus Studio)
Inspired by: CSOP - Client-Side Orchestration Protocol
Learn more:
- 📖 CSOP: https://github.com/Nexus-Studio-CEO/CSOP
- 📖 RAFT Protocol: RAFT_PROTOCOL.md
- 📖 Roadmap: ROADMAP.md
🚀 Happy building with FrontendRAFT!
