generated from adobe-rnd/aem-boilerplate-xcom
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
87 lines (70 loc) · 2.27 KB
/
index.js
File metadata and controls
87 lines (70 loc) · 2.27 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/* eslint-disable import/no-cycle */
// Drop-in Tools
import { events } from '@dropins/tools/event-bus.js';
import {
removeFetchGraphQlHeader,
setEndpoint,
setFetchGraphQlHeader,
} from '@dropins/tools/fetch-graphql.js';
import * as authApi from '@dropins/storefront-auth/api.js';
// Libs
import { getConfigValue, getCookie } from '../configs.js';
export const getUserTokenCookie = () => getCookie('auth_dropin_user_token');
// Update auth headers
const setAuthHeaders = (state) => {
if (state) {
const token = getUserTokenCookie();
setFetchGraphQlHeader('Authorization', `Bearer ${token}`);
} else {
removeFetchGraphQlHeader('Authorization');
authApi.removeFetchGraphQlHeader('Authorization');
}
};
const persistCartDataInSession = (data) => {
if (data?.id) {
sessionStorage.setItem('DROPINS_CART_ID', data.id);
} else {
sessionStorage.removeItem('DROPINS_CART_ID');
}
};
export default async function initializeDropins() {
const init = async () => {
// Set auth headers on authenticated event
events.on('authenticated', setAuthHeaders);
// Cache cart data in session storage
events.on('cart/data', persistCartDataInSession, { eager: true });
// on page load, check if user is authenticated
const token = getUserTokenCookie();
// set auth headers
setAuthHeaders(!!token);
// Event Bus Logger
events.enableLogger(true);
// Set Fetch Endpoint (Global)
setEndpoint(getConfigValue('commerce-core-endpoint'));
// Initialize Global Drop-ins
await import('./auth.js');
import('./cart.js');
events.on('aem/lcp', async () => {
// Recaptcha
await import('@dropins/tools/recaptcha.js').then(({ setConfig }) => {
setConfig();
});
});
};
// re-initialize on prerendering changes
document.addEventListener('prerenderingchange', initializeDropins, { once: true });
return init();
}
export function initializeDropin(cb) {
let initialized = false;
const init = async (force = false) => {
// prevent re-initialization
if (initialized && !force) return;
// initialize drop-in
await cb();
initialized = true;
};
// re-initialize on prerendering changes
document.addEventListener('prerenderingchange', () => init(true), { once: true });
return init;
}