Code Examples

Learn by example with real, working Cortex code

Creating Your First Actor

import { ActorSystem, EventBus } from 'cortex'; const eventBus = EventBus.getInstance(); const actorSystem = new ActorSystem(eventBus); // Define an actor class GreeterActor { async handle(message: any) { console.log(`Hello, ${message.name}!`); } } // Create and send a message const greeter = actorSystem.createActor(GreeterActor); greeter.send({ name: 'Cortex' });
Output:
Hello, Cortex!

Using the Event Bus

import { EventBus } from 'cortex'; const bus = EventBus.getInstance(); // Subscribe to events bus.on('user:created', (event) => { console.log(`User created: ${event.userId}`); }); // Publish events bus.emit('user:created', { userId: 'user-123', email: 'user@example.com' });
Output:
User created: user-123

Building a REST API

import { CortexHttpServer } from 'cortex'; const server = new CortexHttpServer(3000); server.get('/api/users/:id', (req, res) => { const userId = req.params.id; res.writeHead(200, {'Content-Type': 'application/json'}); res.end(JSON.stringify({ id: userId, name: 'John Doe' })); }); await server.start(); console.log('Server listening on port 3000');
Response:
{"id":"123","name":"John Doe"}

Circuit Breaker Pattern

import { CircuitBreaker } from 'cortex/resilience'; const breaker = new CircuitBreaker({ threshold: 5, timeout: 60000 }); async function unreliableOperation() { return breaker.execute(async () => { // Your operation here return await fetchExternalAPI(); }); }
Protects against cascading failures through automatic circuit opening

Middleware Stack

const server = new CortexHttpServer(3000); // Global middleware server.use((req, res, next) => { console.log(`${req.method} ${req.url}`); next(); }); // Route with middleware server.get('/protected', authMiddleware, loggingMiddleware, (req, res) => { res.end('Protected endpoint'); } );
All requests are logged and authenticated before reaching the handler

Health Checks

import { HealthCheckRegistry } from 'cortex/observability'; const registry = new HealthCheckRegistry(); registry.register('database', async () => { return await db.ping(); }); server.registerHealthEndpoint(registry); // GET /health // Returns overall system health status
Health Status: UP
Database: UP