Moleculer HTTP Client Mixin

0.4.2 · active · verified Wed Apr 22

This package provides an HTTP client mixin for Moleculer microservices, enabling them to make requests to external REST APIs. It is currently at version 0.4.2 and wraps the popular `got` library for HTTP requests. While there's no explicit release cadence stated for this particular mixin, it generally follows the Moleculer ecosystem's development pace. Its key differentiators include seamless integration into Moleculer services via mixins, providing declarative HTTP actions (`get`, `post`, `put`, `patch`), and centralized configuration for logging, error handling, and `got` options within the service settings. This approach simplifies HTTP communication within a microservice architecture, abstracting common concerns like request/response logging and error formatting directly into the service lifecycle.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates creating a Moleculer service using the `moleculer-http-client` mixin, configuring its HTTP client settings, and then using the mixin's `get` and `post` actions to communicate with an external REST API, including basic error handling.

import { ServiceBroker } from 'moleculer';
import HttpClientMixin from 'moleculer-http-client';

const broker = new ServiceBroker({
    logger: true, // Enable console logger
    logLevel: 'info' // Set logging level
});

broker.createService({
    name: "myApiConsumer",
    mixins: [HttpClientMixin],
    settings: {
        httpClient: {
            logging: true, // Log outgoing requests and incoming responses
            responseFormatter: "body", // Only return the response body by default
            defaultOptions: {
                // Default options passed directly to the 'got' client
                headers: {
                    'User-Agent': 'moleculer-http-client-example/1.0',
                },
                timeout: {
                    request: 5000 // 5 seconds timeout for all requests
                }
            }
        }
    },
    actions: {
        async fetchPosts(ctx) {
            this.logger.info(`Attempting to fetch post from: ${ctx.params.url}`);
            try {
                // Call the 'get' action provided by the mixin
                const response = await ctx.call("myApiConsumer.get", {
                    url: "https://jsonplaceholder.typicode.com/posts/1"
                });
                this.logger.info("Successfully fetched post:", JSON.stringify(response));
                return response;
            } catch (error) {
                this.logger.error("Error fetching post:", error.message);
                throw error; // Re-throw to propagate error in Moleculer
            }
        },
        async submitData(ctx) {
            this.logger.info(`Attempting to submit data to: ${ctx.params.url}`);
            try {
                // Call the 'post' action provided by the mixin
                const response = await ctx.call("myApiConsumer.post", {
                    url: "https://jsonplaceholder.typicode.com/posts",
                    json: {
                        title: 'foo',
                        body: 'bar',
                        userId: 1,
                    }
                });
                this.logger.info("Successfully submitted data (ID: %s)", response.id);
                return response;
            } catch (error) {
                this.logger.error("Error submitting data:", error.message);
                throw error;
            }
        }
    }
});

async function runExample() {
    await broker.start();
    broker.logger.info("Broker started. Calling fetchPosts action...");
    await broker.call("myApiConsumer.fetchPosts", { url: "https://jsonplaceholder.typicode.com/posts/1" });

    broker.logger.info("\nCalling submitData action...");
    await broker.call("myApiConsumer.submitData", { url: "https://jsonplaceholder.typicode.com/posts" });

    await broker.stop();
}

runExample();

view raw JSON →