Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/mixpanel analytics #11

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,22 @@
import { Hono } from 'hono';
import { BlankSchema } from 'hono/types';
import { cors } from 'hono/cors';
import { callAPI, computeTimeAgo } from './utils';
import { callAPI, computeTimeAgo, trackAnalytics } from './utils';
import { TIME_FROM_AGO } from './constants';

const app = new Hono<
{
Bindings: {
BIRDEYE_API_KEY: string;
MIXPANEL_TOKEN: string;
};
},
BlankSchema,
'/'
>();

app.use('*', trackAnalytics);

app.all(
'*',
cors({
Expand Down
46 changes: 46 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Context } from 'hono';
import { TIME_FROM_AGO } from './constants';

const DEFAULT_TTL_IN_SECONDS = 30;
Expand Down Expand Up @@ -44,3 +45,48 @@ export const computeTimeAgo = (time: number, timeAgo: TIME_FROM_AGO) => {

return time - secondsToSubtract;
};

export const getAddressKeys = (query: Record<string, string>): string[] => {
const addressKeys: string[] = [];

Object.entries(query).forEach(([key, value]) => {
// We have params with different names, but has the word address in it
if (key.toLowerCase().includes('address')) {
addressKeys.push(value);
}
});

return addressKeys;
};

// Mp doesnt worrk well with cloudflare worker, so sending HTTPS request instead
// https://developer.mixpanel.com/reference/track-event
export const trackAnalytics = async (c: Context, next: () => Promise<void>) => {
const token = c.env.MIXPANEL_TOKEN;

const address = getAddressKeys(c.req.query());
const properties = JSON.stringify([ {
properties: {
address,
token,
endpoint: c.req.path,
distinct_id: Date.now(),
$insert_id: Math.random().toString(36)
},
event: 'birdeye-proxy'
}]);

try {
fetch('https://api.mixpanel.com/track', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: properties
});
} catch (error) {
console.error('Failed to track analytics:', error);
} finally {
await next();
}
};