Skip to content

Commit

Permalink
feat: add usage metrics
Browse files Browse the repository at this point in the history
  • Loading branch information
benjaminshafii committed Apr 19, 2024
1 parent 2bda5fd commit 23affaa
Show file tree
Hide file tree
Showing 4 changed files with 81 additions and 2 deletions.
15 changes: 15 additions & 0 deletions app/lib/posthog.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// app/posthog.js
import { PostHog } from 'posthog-node'

export default function PostHogClient() {
if (!process.env.NEXT_PUBLIC_POSTHOG_KEY) {
return null
}

const posthogClient = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_KEY, {
host: process.env.NEXT_PUBLIC_POSTHOG_HOST || 'https://app.posthog.com',
flushAt: 1,
flushInterval: 0
})
return posthogClient
}
52 changes: 52 additions & 0 deletions app/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"next": "13.5.4",
"openai": "^4.33.1",
"postcss": "8.4.31",
"posthog-node": "^4.0.0",
"react": "18.2.0",
"react-dom": "18.2.0",
"tailwind-merge": "^1.14.0",
Expand Down
15 changes: 13 additions & 2 deletions app/pages/api/name.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { verifyKey } from "@unkey/api";
import type { NextApiRequest, NextApiResponse } from "next";
import PosthogClient from "../../lib/posthog";

type ResponseData = {
message: string;
Expand All @@ -11,7 +12,7 @@ export default async function handler(
) {
// if ENABLE_USER_MANAGEMENT=true in .env file, then we need to check for the Authorization header
if (process.env.ENABLE_USER_MANAGEMENT == "true") {
console.log("ENABLE_USER_MANAGEMENT", process.env.ENABLE_USER_MANAGEMENT)
console.log("ENABLE_USER_MANAGEMENT", process.env.ENABLE_USER_MANAGEMENT);

const header = req.headers.authorization;
console.log("header", header);
Expand All @@ -21,6 +22,16 @@ export default async function handler(
const token = header.replace("Bearer ", "");
const { result, error } = await verifyKey(token);

const client = PosthogClient();

if (client && result?.ownerId) {
client.capture({
distinctId: result?.ownerId,
event: "call-api",
properties: { endpoint: "name" },
});
}

if (error) {
console.error(error.message);
return res.status(500).json({ message: "Internal Server Error" });
Expand All @@ -32,7 +43,7 @@ export default async function handler(
}
try {
const apiKey = process.env.OPENAI_API_KEY || "";
console.log("apiKey", apiKey)
console.log("apiKey", apiKey);
const model = "gpt-3.5-turbo";
const data = {
...req.body,
Expand Down

0 comments on commit 23affaa

Please sign in to comment.