Skip to content

Commit

Permalink
chore: use async track of segment (#304)
Browse files Browse the repository at this point in the history
* chore: add log for telemetry

* chore: use async track
  • Loading branch information
eliobricenov authored Aug 8, 2023
1 parent b2ad0ab commit 2bf0c02
Showing 1 changed file with 13 additions and 6 deletions.
19 changes: 13 additions & 6 deletions docs/pages/api/telemetry/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Analytics } from "@segment/analytics-node";
import { Analytics, TrackParams } from "@segment/analytics-node";
import { NextApiRequest, NextApiResponse } from "next";

if (!process.env.SEGMENT_WRITE_KEY) {
Expand All @@ -14,6 +14,15 @@ const analytics = new Analytics({
maxEventsInBatch: 1,
});

const asyncTrack = (payload: TrackParams) => {
return new Promise<void>((resolve, reject) => {
analytics.track(payload, (err) => {
if (err) reject(err);
resolve();
});
});
};

export default async function forwardTelemetry(
req: NextApiRequest,
res: NextApiResponse
Expand All @@ -24,16 +33,14 @@ export default async function forwardTelemetry(
});
}

res.status(200).json({
message: "Telemetry data processed successfully.",
});

try {
await analytics.track(req.body);
await asyncTrack(req.body);
res.status(200).json({ success: true });
} catch (e) {
console.error("Error processing telemetry data:", {
error: e,
body: req.body,
});
res.status(500).json({ error: "Server error" });
}
}

1 comment on commit 2bf0c02

@vercel
Copy link

@vercel vercel bot commented on 2bf0c02 Aug 8, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.