moleculerjs / moleculer-channels

Reliable messages for Moleculer services via external queue/channel/topic.
MIT License
72 stars 15 forks source link

Context-based handlers #64

Closed icebob closed 1 year ago

icebob commented 1 year ago

This PR adds Context-based functionality:

This functions works with all adapters.

Enable the function globally for all channel handlers

// moleculer.config.js
const ChannelsMiddleware = require("@moleculer/channels").Middleware;

module.exports = {
    logger: true,

    middlewares: [
        ChannelsMiddleware({
            adapter: "redis://localhost:6379",
            // Enable context in all channel handlers 
            context: true
        })
    ]
};

Call with context:

broker.createService({
    name: "publisher",
    actions: {
        async publish(ctx) {
            await broker.sendToChannel("my.topic", { a: 5, b: "John" }, {
                ctx,
                headers: { myHeader: "123" }
            });
        }
    }
});

Context in handler

The Context is always created regardless of whether it was passed at sendToChannel

module.exports = {
    name: "sub1",
    channels: {
        "my.topic": {
            context: true, // Unless not enabled it globally
            async handler(ctx, raw) {
                // Original `msg` in `ctx.params`
                this.logger.info("Processing...", ctx.params, ctx.meta);
            }
        }
    }
}

Tracing

Register channel tracing middleware

//moleculer.config.js
const TracingMiddleware = require("@moleculer/channels").Tracing;

module.exports = {
    logger: true,

    middlewares: [
        ChannelsMiddleware({
            adapter: "redis://localhost:6379",
            // Enable context in all channel handlers 
            context: true
        }),
        TracingMiddleware()
    ]
};

You can fine-tuning tracing tags and span name in tracing channel property similar to actions.

Customize tags and span name

broker.createService({
    name: "sub1",
    channels: {
        "my.topic": {
            context: true,
            tracing: {
                spanName: ctx => `My custom span: ${ctx.params.id}`
                tags: {
                    params: true,
                    meta: true
                }
            },
            async handler(ctx, raw) {
                // ...
            }
        }
    }
});