cube-ms
v1.1.3
Published
A simple microservice framework for Node.js
Readme
cubeforall-microservice-v2
A powerful framework for creating Express-based microservices with WebSocket support and an integrated logging system using MongoDB capped collections.
Features
Service Framework
- Express Integration: Quickly create an HTTP server with middleware support.
- WebSocket Support: Built-in WebSocket server for real-time communication.
- Dynamic Routes: Easily add custom HTTP routes.
- Middleware Management: Includes prebuilt middlewares like API key validation and whitelisting.
Logging Utility
- Structured Logging: Store logs with metadata in MongoDB capped collections.
- Console Log Streaming: Real-time log streaming to the console.
- Tagging System: Automatically tag logs based on their content.
- Buffered Writes: Batch log writes to MongoDB for optimized performance.
Installation
Install the package via npm:
npm install cubeforall-microservice-v2View the package on npm.
Usage
Service Creation
Import the CreateService Function
import { CreateService } from "cubeforall-microservice-v2";Create a Service
const service = CreateService({
port: 3000,
appName: "MyApp",
serviceName: "MyService",
containerName: "MyContainer",
});
// Add a route
service.addRoute("get", "/ping", (req, res) => {
res.send("pong");
});
// Start a WebSocket server
service.onCommand((command) => {
console.log("Command received:", command);
});Available Methods:
addRoute(method, path, handler, middlewares): Add an HTTP route.onCommand(callback): Set a handler for WebSocket commands.getService(url): Create agotinstance for external service calls.getStore(url): Connect to a database store.getStream(url): Connect to a database stream.setupChannel(name, sourceObj, dbName, collectionName, filter): Set up a WebSocket channel for real-time data streaming.
Logging Utility
Import the Logging Functions
import {
CreateLogger,
StartConsoleLog,
StopConsoleLog,
} from "cubeforall-microservice-v2";Create a Logger Instance
const logger = CreateLogger("MyApp", "MyService", "MyContainer");
logger.info("Application started successfully.");
logger.error("An error occurred", { errorCode: 500 });
logger.setKeyTags(["performance", "monitoring"]);Start Real-Time Log Streaming to Console
await StartConsoleLog("MyApp", "MyService", "MyContainer", [
{ level: "error" },
]);Stop Real-Time Log Streaming
await StopConsoleLog();Environment Variables
| Variable | Default Value | Description |
| ----------------- | --------------------------- | ----------------------------------------- |
| LOG_DB_URL | mongodb://localhost:27017 | MongoDB connection URL. |
| LOG_MAX_RECORDS | 10000 | Maximum records in the capped collection. |
| LOG_MAX_BYTES | 10485760 (10MB) | Maximum size of the capped collection. |
API Documentation
Service Framework: CreateService
Parameters:
| Parameter | Type | Default Value | Description |
| --------------- | --------- | ------------------ | -------------------------------------------- |
| port | number | undefined | The port for the server to listen on. |
| appName | string | app.<UUID> | The name of the application. |
| serviceName | string | service.<UUID> | The name of the service. |
| containerName | string | container.<UUID> | The container identifier. |
| no_console | boolean | false | Disables console logging when set to true. |
Logging Utility
CreateLogger(appName, serviceName, containerName, log_id)
Methods:
| Method | Description |
| ------------------ | ------------------------------------------------------------- |
| debug(...args) | Logs a debug-level message. |
| info(...args) | Logs an info-level message. |
| error(...args) | Logs an error-level message. |
| stats(...args) | Logs a stats-level message. |
| setLogId(id) | Sets a new unique log ID. |
| getLogId() | Returns the current log ID. |
| setKeyTags(tags) | Sets global tags for logs (e.g., ["monitoring", "errors"]). |
Example Usage
Service with Integrated Logging
import {
CreateService,
CreateLogger,
StartConsoleLog,
StopConsoleLog,
} from "cubeforall-microservice-v2";
const service = CreateService({
port: 3000,
appName: "MyApp",
serviceName: "MyService",
containerName: "MyContainer",
});
// Add routes
service.addRoute("get", "/health", (req, res) => {
res.json({ status: "healthy" });
});
// Start WebSocket server
service.onCommand((command) => {
console.log("Command received:", command);
});
// Start logging to console
await StartConsoleLog("MyApp", "MyService", "MyContainer");
// Stop logging
await StopConsoleLog();Notes
- Capped Collections: Logs are stored in capped collections, automatically removing old records as the limit is reached.
- Retry Logic: Services and streams reconnect automatically on failure.
- Buffered Writes: Logs are batched for improved performance.
Contributing
Feel free to open issues or submit pull requests to improve this package.
For more information, visit the npm package page.
