Skip to content

Commit

Permalink
fetchUsers: fix caching bug
Browse files Browse the repository at this point in the history
  • Loading branch information
tomfa committed Sep 30, 2023
1 parent 5305e56 commit a11137e
Showing 1 changed file with 6 additions and 4 deletions.
10 changes: 6 additions & 4 deletions src/data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import fetch from "node-fetch";
import { ChatBot, User } from "./types";

let userData: User[] = [];
let lastUpdated: number | undefined;

async function isRedirected(url: string) {
const data = await fetch(url, { method: "HEAD" });
Expand All @@ -28,12 +29,13 @@ const hasImageLazy = (user: User) => async () => {

export async function fetchUsers({
app,
refresh = false,
useCache = true,
}: {
app: ChatBot;
refresh?: false;
useCache?: true;
}): Promise<User[]> {
if (userData && !refresh) {
const yesterday = new Date(Date.now() - 24 * 7 * 60 * 60 * 1000);
if (useCache && lastUpdated && lastUpdated > yesterday.getTime()) {
return userData;
}
try {
Expand All @@ -55,7 +57,7 @@ export async function fetchUsers({
hasImage: hasImageLazy(m as User),
})
);

lastUpdated = Date.now();
return userData;
} catch (error) {
console.error(error);
Expand Down

0 comments on commit a11137e

Please sign in to comment.