Skip to content

Commit 0f3197b

Browse files
committed
Update apollo.js
1 parent f926bdb commit 0f3197b

File tree

1 file changed

+16
-38
lines changed

1 file changed

+16
-38
lines changed

plugins/apollo.js

Lines changed: 16 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,11 @@ import {
77

88
import { provideApolloClient } from "@vue/apollo-composable";
99

10-
const SEVEN_DAYS = 7 * 24 * 60 * 60 * 1000; // 7 days in milliseconds
11-
1210
export default defineNuxtPlugin((nuxtApp) => {
11+
const cookie = useCookie("woo-session", {
12+
maxAge: 1_209_600, // 14 days
13+
sameSite: "lax",
14+
});
1315
const config = useRuntimeConfig();
1416

1517
const httpLink = createHttpLink({
@@ -20,25 +22,13 @@ export default defineNuxtPlugin((nuxtApp) => {
2022
/**
2123
* If session data exist in local storage, set value as session header.
2224
*/
23-
const sessionData = process.client
24-
? JSON.parse(localStorage.getItem("woo-session"))
25-
: null;
2625

27-
if (sessionData && sessionData.token && sessionData.createdTime) {
28-
const { token, createdTime } = sessionData;
29-
30-
// Check if the token is older than 7 days
31-
if (Date.now() - createdTime > SEVEN_DAYS) {
32-
// If it is, delete it
33-
localStorage.removeItem("woo-session");
34-
} else {
35-
// If it's not, use the token
36-
operation.setContext(() => ({
37-
headers: {
38-
"woocommerce-session": `Session ${token}`,
39-
},
40-
}));
41-
}
26+
if (process.client && cookie.value) {
27+
operation.setContext(() => ({
28+
headers: {
29+
"woocommerce-session": `Session ${cookie.value}`,
30+
},
31+
}));
4232
}
4333

4434
return forward(operation);
@@ -55,18 +45,11 @@ export default defineNuxtPlugin((nuxtApp) => {
5545
response: { headers },
5646
} = context;
5747

58-
const session = headers.get("woocommerce-session");
48+
const session = headers.get("woocommerce-session") || cookie.value;
5949

60-
if (session && process.client) {
61-
if (session === "false") {
62-
// Remove session data if session destroyed.
63-
localStorage.removeItem("woo-session");
64-
// Update session new data if changed.
65-
} else if (!localStorage.getItem("woo-session")) {
66-
localStorage.setItem(
67-
"woo-session",
68-
JSON.stringify({ token: session, createdTime: Date.now() })
69-
);
50+
if (process.client && session) {
51+
if (session !== cookie.value) {
52+
cookie.value = session;
7053
}
7154
}
7255
return response;
@@ -102,11 +85,6 @@ export default defineNuxtPlugin((nuxtApp) => {
10285
provideApolloClient(apolloClient);
10386

10487
nuxtApp.hook("apollo:auth", ({ token }) => {
105-
if (process.client) {
106-
const sessionData = JSON.parse(localStorage.getItem("woo-session"));
107-
if (sessionData && sessionData.token) {
108-
token.value = sessionData.token;
109-
}
110-
}
88+
token.value = cookie.value;
11189
});
112-
});
90+
});

0 commit comments

Comments
 (0)