-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.js
71 lines (63 loc) · 1.97 KB
/
middleware.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { NextResponse } from "next/server";
import { fetchPetData } from "./utils/fetchPetData";
const COOKIE_NAME = "pets-data";
const TWENTY_FOUR_HOURS = 24 * 60 * 60 * 1000;
export async function middleware(request) {
// Initiate Response
const response = NextResponse.next();
// Get the 'pets-data' cookie from the request
const needPetData = request.headers.get("pet-data");
// If there's no pets-data cookie or it needs a refresh, fetch data
if (needPetData) {
try {
// Call the API to get pet data
const apiResponse = await fetch(`${request.nextUrl.origin}/api/animals`, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
credentials: "same-origin",
});
const data = await apiResponse.json();
console.log("Is Array: " + Array.isArray(data));
// Create the cookie value with only the first 10 objects
response.headers.set(
"pet-data",
JSON.stringify(
{
data: data,
timestamp: Date.now(),
totalCount: data.length,
},
(key, value) => {
// Optionally clean or filter out unwanted characters
if (typeof value === "string") {
return value.replace(/[^\x00-\x7F]/g, ""); // Removes non-ASCII characters
}
return value;
}
)
);
console.log("Data Fetched");
} catch (error) {
console.error("Error fetching pet data:", error);
return NextResponse.json(
{ error: "Failed to fetch pet data" },
{ status: 500 }
);
}
} else {
console.log("Pet data cookie is valid, no refresh needed");
}
return response;
}
function needsRefresh(cookie) {
try {
const cookieData = JSON.parse(cookie);
const now = Date.now();
return now - cookieData.timestamp > TWENTY_FOUR_HOURS;
} catch (error) {
console.error("Error parsing cookie data:", error);
return true;
}
}