Skip to content

Commit

Permalink
adds kv
Browse files Browse the repository at this point in the history
  • Loading branch information
elliotBraem committed Dec 13, 2024
1 parent 11ad489 commit 87c733a
Showing 1 changed file with 18 additions and 6 deletions.
24 changes: 18 additions & 6 deletions src/app/lib/twitter.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Scraper } from "agent-twitter-client";
import { kv } from '@vercel/kv';

interface TwitterCookie {
key: string;
Expand Down Expand Up @@ -33,10 +34,8 @@ export class TwitterService {
private async setCookiesFromArray(cookiesArray: TwitterCookie[]) {
const cookieStrings = cookiesArray.map(
(cookie) =>
`${cookie.key}=${cookie.value}; Domain=${cookie.domain}; Path=${cookie.path}; ${
cookie.secure ? "Secure" : ""
}; ${cookie.httpOnly ? "HttpOnly" : ""}; SameSite=${
cookie.sameSite || "Lax"
`${cookie.key}=${cookie.value}; Domain=${cookie.domain}; Path=${cookie.path}; ${cookie.secure ? "Secure" : ""
}; ${cookie.httpOnly ? "HttpOnly" : ""}; SameSite=${cookie.sameSite || "Lax"
}`,
);
await this.client.setCookies(cookieStrings);
Expand All @@ -46,7 +45,13 @@ export class TwitterService {
username: string,
): Promise<TwitterCookie[] | null> {
try {
// Try to read cookies from a local cache file
// Try Vercel KV first in production
if (process.env.VERCEL) {
const cookies = await kv.get<TwitterCookie[]>(`twitter_cookies:${username}`);
return cookies;
}

// Fallback to filesystem in development
const fs = await import("fs/promises");
const path = await import("path");
const cookiePath = path.join(process.cwd(), ".twitter-cookies.json");
Expand All @@ -58,14 +63,21 @@ export class TwitterService {
return cache[username];
}
} catch (error) {
// If file doesn't exist or is invalid, return null
// If storage access fails or is invalid, return null
return null;
}
return null;
}

private async cacheCookies(username: string, cookies: TwitterCookie[]) {
try {
// Use Vercel KV in production
if (process.env.VERCEL) {
await kv.set(`twitter_cookies:${username}`, cookies);
return;
}

// Use filesystem in development
const fs = await import("fs/promises");
const path = await import("path");
const cookiePath = path.join(process.cwd(), ".twitter-cookies.json");
Expand Down

0 comments on commit 87c733a

Please sign in to comment.