n8n/packages/cli/src/posthog/index.ts
Tomi Turtiainen 9a1cc56806
fix: Set '@typescript-eslint/return-await' rule to 'always' for node code (no-changelog) (#8363)
Co-authored-by: कारतोफ्फेलस्क्रिप्ट™ <aditya@netroy.in>
2024-01-17 17:08:50 +02:00

59 lines
1.6 KiB
TypeScript

import { Service } from 'typedi';
import type { PostHog } from 'posthog-node';
import type { FeatureFlags, ITelemetryTrackProperties } from 'n8n-workflow';
import { InstanceSettings } from 'n8n-core';
import config from '@/config';
import type { PublicUser } from '@/Interfaces';
@Service()
export class PostHogClient {
private postHog?: PostHog;
constructor(private readonly instanceSettings: InstanceSettings) {}
async init() {
const enabled = config.getEnv('diagnostics.enabled');
if (!enabled) {
return;
}
const { PostHog } = await import('posthog-node');
this.postHog = new PostHog(config.getEnv('diagnostics.config.posthog.apiKey'), {
host: config.getEnv('diagnostics.config.posthog.apiHost'),
});
const logLevel = config.getEnv('logs.level');
if (logLevel === 'debug') {
this.postHog.debug(true);
}
}
async stop(): Promise<void> {
if (this.postHog) {
return this.postHog.shutdown();
}
}
track(payload: { userId: string; event: string; properties: ITelemetryTrackProperties }): void {
this.postHog?.capture({
distinctId: payload.userId,
sendFeatureFlags: true,
...payload,
});
}
async getFeatureFlags(user: Pick<PublicUser, 'id' | 'createdAt'>): Promise<FeatureFlags> {
if (!this.postHog) return {};
const fullId = [this.instanceSettings.instanceId, user.id].join('#');
// cannot use local evaluation because that requires PostHog personal api key with org-wide
// https://github.com/PostHog/posthog/issues/4849
return await this.postHog.getAllFlags(fullId, {
personProperties: {
created_at_timestamp: user.createdAt.getTime().toString(),
},
});
}
}