1.1.0 • Published 7 months ago

cube-ms v1.1.0

Weekly downloads
-
License
MIT
Repository
-
Last release
7 months ago

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-v2

View 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 a got instance 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

VariableDefault ValueDescription
LOG_DB_URLmongodb://localhost:27017MongoDB connection URL.
LOG_MAX_RECORDS10000Maximum records in the capped collection.
LOG_MAX_BYTES10485760 (10MB)Maximum size of the capped collection.

API Documentation

Service Framework: CreateService

Parameters:

ParameterTypeDefault ValueDescription
portnumberundefinedThe port for the server to listen on.
appNamestringapp.<UUID>The name of the application.
serviceNamestringservice.<UUID>The name of the service.
containerNamestringcontainer.<UUID>The container identifier.
no_consolebooleanfalseDisables console logging when set to true.

Logging Utility

CreateLogger(appName, serviceName, containerName, log_id)

Methods:

MethodDescription
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

  1. Capped Collections: Logs are stored in capped collections, automatically removing old records as the limit is reached.
  2. Retry Logic: Services and streams reconnect automatically on failure.
  3. 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.