Skip to content

Commit

Permalink
fix: Refactor PostHog to handle short-lived environments (#607)
Browse files Browse the repository at this point in the history
  • Loading branch information
luis-herasme authored Oct 28, 2024
1 parent ba1d783 commit c3fcc4f
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 7 deletions.
6 changes: 5 additions & 1 deletion packages/api/src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { getBlobStorageManager } from "@blobscan/blob-storage-manager";
import { prisma } from "@blobscan/db";
import { env } from "@blobscan/env";

import { posthog } from "./posthog";
import { PostHogClient } from "./posthog";

type NextHTTPRequest = CreateNextContextOptions["req"];

Expand Down Expand Up @@ -87,6 +87,8 @@ export function createTRPCContext(
apiClient,
});

const posthog = PostHogClient();

if (posthog) {
const cookies = cookie.parse(opts.req.headers.cookie ?? "");

Expand All @@ -113,6 +115,8 @@ export function createTRPCContext(
method: opts.req.method,
},
});

await posthog.shutdown();
}

return {
Expand Down
16 changes: 10 additions & 6 deletions packages/api/src/posthog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,14 @@ import { PostHog } from "posthog-node";

import { env } from "@blobscan/env";

let posthog: PostHog | null = null;

if (env.POSTHOG_ID) {
posthog = new PostHog(env.POSTHOG_ID, { host: env.POSTHOG_HOST });
export function PostHogClient(): PostHog | null {
if (!env.POSTHOG_ID) {
return null;
}

return new PostHog(env.POSTHOG_ID, {
host: env.POSTHOG_HOST,
flushAt: 1,
flushInterval: 0,
});
}

export { posthog };

0 comments on commit c3fcc4f

Please sign in to comment.