feat (Worker): add a worker to check and adjust the TikTok graph
This commit is contained in:
@@ -16,12 +16,14 @@ export async function GET() {
|
||||
}
|
||||
|
||||
if (process.env.NODE_ENV === "development") {
|
||||
const user = await prisma.user.findUnique({ where: { id: userId } });
|
||||
return NextResponse.json({
|
||||
followers: 124,
|
||||
likes: 856,
|
||||
videoCount: 1,
|
||||
displayName: "CrowMate studio",
|
||||
avatarUrl: "",
|
||||
plan: (user as any)?.plan ?? "free",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -36,20 +38,16 @@ export async function GET() {
|
||||
if (expiresAt.getTime() - Date.now() < 60_000) {
|
||||
try {
|
||||
const refreshed = await refreshAccessToken(refreshToken);
|
||||
const newExpiresAt = new Date(Date.now() + refreshed.expires_in * 1000);
|
||||
|
||||
await prisma.tikTokToken.update({
|
||||
where: { userId },
|
||||
data: {
|
||||
accessToken: refreshed.access_token,
|
||||
refreshToken: refreshed.refresh_token,
|
||||
expiresAt: newExpiresAt,
|
||||
expiresAt: new Date(Date.now() + refreshed.expires_in * 1000),
|
||||
},
|
||||
});
|
||||
|
||||
accessToken = refreshed.access_token;
|
||||
refreshToken = refreshed.refresh_token;
|
||||
expiresAt = newExpiresAt;
|
||||
} catch (err) {
|
||||
console.error("[TikTok stats refresh error]", err);
|
||||
return NextResponse.json({ error: "Token refresh failed" }, { status: 401 });
|
||||
@@ -58,7 +56,38 @@ export async function GET() {
|
||||
|
||||
try {
|
||||
const stats = await fetchUserStats(accessToken, openId);
|
||||
return NextResponse.json(stats);
|
||||
|
||||
// Upsert TrackedAccount + snapshot automatique
|
||||
try {
|
||||
let account = await prisma.trackedAccount.findFirst({
|
||||
where: { userId, platform: "tiktok" },
|
||||
});
|
||||
if (!account) {
|
||||
account = await prisma.trackedAccount.create({
|
||||
data: {
|
||||
userId,
|
||||
platform: "tiktok",
|
||||
username: stats.displayName ?? openId,
|
||||
accountId: openId,
|
||||
},
|
||||
});
|
||||
}
|
||||
await prisma.snapshot.create({
|
||||
data: {
|
||||
accountId: account.id,
|
||||
followers: stats.followers ?? 0,
|
||||
likes: stats.likes ?? 0,
|
||||
videoCount: stats.videoCount ?? 0,
|
||||
views: 0,
|
||||
},
|
||||
});
|
||||
} catch (snapshotErr) {
|
||||
console.error("[TikTok snapshot save error]", snapshotErr);
|
||||
}
|
||||
|
||||
// Inclure le plan dans la réponse
|
||||
const user = await prisma.user.findUnique({ where: { id: userId } });
|
||||
return NextResponse.json({ ...stats, plan: (user as any)?.plan ?? "free" });
|
||||
} catch (err) {
|
||||
console.error("[TikTok stats fetch error]", err);
|
||||
return NextResponse.json({ error: "Failed to fetch stats" }, { status: 500 });
|
||||
|
||||
Reference in New Issue
Block a user