Reputation: 1
I want to implement custom middleware in my Angular application to modify Segment tracking events dynamically before they are sent. The goal is to filter, modify, or enrich events based on specific conditions or rules.
Here’s the approach I’m considering:
import { Injectable } from '@angular/core';
import Analytics from 'analytics-node';
@Injectable({
providedIn: 'root',
})
export class SegmentService {
private analytics: Analytics;
private middleware: Array<(event: any) => any> = [];
constructor() {
this.analytics = new Analytics('YOUR_WRITE_KEY');
}
use(middlewareFn: (event: any) => any) {
this.middleware.push(middlewareFn);
}
trackEvent(event: string, properties: any, context?: any) {
let eventObj = { event, properties, context };
// Apply middleware
this.middleware.forEach((fn) => {
eventObj = fn(eventObj);
});
this.analytics.track(eventObj);
}
}
My questions are:
Upvotes: 0
Views: 60
Reputation: 5124
Middleware is not a concept native to angular. You can use interceptors, guards, etc, but I'm not familiar with a way to automatically hook to a changed dto in angular and modify it.
Your service can use observables or singals (from angular 16 forward), but in any case you will have to register your service to the observables whenever you want to use the value. However, this is not the approach I'd take, since it is async and would be cumbersome to use.
A simpler, more angular-like approach would be to just use a service like this:
@Injectable()
export class MiddlewareService {
constructor(private readonly handler1: Handler1,
private readonly handler2: Handler2)
}
public doStuff(myData: Data): Data {
//run your handlers and return the modified data
}
}
And then inject it and use it wherever you like (Don't forget to define your handlers as injectable services as well).
Upvotes: 0