UNPKG

node-consul-service

Version:

A robust Node.js service that integrates with HashiCorp Consul for service discovery and configuration management. This service provides a comprehensive solution for managing distributed systems and microservices architecture, making it easier to handle s

246 lines (194 loc) 6.51 kB
# Node Consul Service A robust Node.js service that integrates with HashiCorp Consul for service discovery and configuration management. This service provides a comprehensive solution for managing distributed systems and microservices architecture, making it easier to handle service communication, health checks, and configuration management in a distributed environment. ## Table of Contents - [Features](#features) - [Prerequisites](#prerequisites) - [Installation](#installation) - [Initialization](#initialization) - [API Documentation](#api-documentation) - [Examples](#examples) - [Contributing](#contributing) - [License](#license) ## Features - **Service Registration & Discovery**: Automatically register and discover services in your distributed system - **Health Checking**: Built-in health check mechanisms for service monitoring - **Service Communication**: Simplified inter-service communication with automatic load balancing - **Service Instance Management**: Easy management of multiple service instances - **Data Linking**: Efficient data aggregation and linking across services - **Caching Support**: Optional caching mechanism for improved performance ## Prerequisites - Node.js (v14 or higher) - HashiCorp Consul server - npm or yarn package manager ## Installation ```bash # Using npm npm install node-consul-service # Using yarn yarn add node-consul-service ``` ## Initialization ### Service Initialization Before using any functions from the library, you must initialize the client first. You can initialize the client by passing configuration options: ```javascript const { initClient } = require('node-consul-service'); await initClient({ host: 'localhost', port: 8500, secure: false, token: 'your-token', // Optional datacenter: 'dc1', // Optional retryAttempts: 3, // Number of connection retry attempts retryDelay: 1000 // Delay between retries in milliseconds }); ``` ### Initialization Features - **Automatic Retry**: Attempts to connect multiple times on failure - **Connection Verification**: Verifies successful connection before proceeding - **State Management**: Tracks initialization state to prevent multiple initializations - **Error Handling**: Clear and helpful error messages ### Complete Usage Example ```javascript const { initClient, registerService } = require('node-consul-service'); async function startService() { try { // Initialize client await initClient({ host: 'localhost', port: 8500, retryAttempts: 3 }); // Register service await registerService({ name: 'my-service', id: 'my-service-1', port: 3000 }); console.log('✅ Service started successfully'); } catch (error) { console.error('❌ Failed to start service:', error); process.exit(1); } } startService(); ``` ## API Documentation ### Core Functions #### Service Registration ```javascript const { registerService } = require('node-consul-service'); await registerService({ name: 'service-name', id: 'service-id', port: 3000, address: 'localhost', check: { name: 'service health check', http: 'http://localhost:3000/health', interval: '10s', timeout: '5s', deregistercriticalserviceafter: '1m' } }); ``` #### Service Communication ```javascript const { callService } = require('node-consul-service'); // Simple GET request const result = await callService('service-name', '/endpoint'); // POST request with data const response = await callService('service-name', { method: 'POST', path: '/endpoint', data: { key: 'value' } }); ``` #### Service Discovery ```javascript const { listServices, getServiceInstances, getRandomServiceInstance } = require('node-consul-service'); // List all registered services const services = await listServices(); // Get all instances of a specific service const instances = await getServiceInstances('service-name'); // Get a random instance of a service const instance = await getRandomServiceInstance('service-name'); ``` ### Data Linking The `dataLink` function provides a powerful way to aggregate and link data from multiple services efficiently. ```javascript const { dataLink } = require('node-consul-service'); const data = [ { userId: '123', name: 'John' }, { userId: '456', name: 'Jane' } ]; const schema = [ { Field: 'userId', // Field name in the original data service: 'user-service', // Target service name path: '/api/users/batch', // API endpoint path cacheGetter: async (ids) => { // Optional function to get data from cache return await cache.getUsers(ids); } } ]; const result = await dataLink(data, schema); ``` #### Schema Properties - `Field`: Field name in the original data that contains the identifier - `service`: Name of the service to be called - `path`: API endpoint path in the target service - `cacheGetter`: Optional function to get data from cache before calling the service ## Examples ### Basic Service Setup ```javascript const { registerService, callService } = require('node-consul-service'); // Register your service await registerService({ name: 'my-service', id: 'my-service-1', port: 3000, address: 'localhost', check: { http: 'http://localhost:3000/health', interval: '10s' } }); // Call another service const response = await callService('other-service', '/api/data'); ``` ### Advanced Data Linking ```javascript const { dataLink } = require('node-consul-service'); // Complex data linking example const orders = [ { orderId: '1', userId: '123', productId: 'P1' }, { orderId: '2', userId: '456', productId: 'P2' } ]; const schema = [ { Field: 'userId', service: 'user-service', path: '/api/users/batch' }, { Field: 'productId', service: 'product-service', path: '/api/products/batch' } ]; const enrichedOrders = await dataLink(orders, schema); ``` ## Contributing We welcome contributions! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change. 1. Fork the repository 2. Create your feature branch (`git checkout -b feature/amazing-feature`) 3. Commit your changes (`git commit -m 'Add some amazing feature'`) 4. Push to the branch (`git push origin feature/amazing-feature`) 5. Open a Pull Request ## License This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.