-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathuserProjectsReady.js
More file actions
49 lines (43 loc) · 1.58 KB
/
userProjectsReady.js
File metadata and controls
49 lines (43 loc) · 1.58 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
import TPEN from "../api/TPEN.js"
// Module-level flag to prevent multiple simultaneous fetches
let isFetching = false
/**
* Utility to handle user projects readiness with caching.
* Checks if projects are already loaded before fetching.
* Triggers fetch if needed, subscribes to event for results.
* @param {Object} ctx - The context to bind the handler to
* @param {Function} handler - The handler function to invoke with projects
* @returns {Function} Unsubscribe function
*/
export const onUserProjectsReady = (ctx, handler) => {
if (!ctx || typeof handler !== 'function') return () => {}
const bound = handler.bind(ctx)
// Check if projects are already cached
try {
if (Array.isArray(TPEN.userProjects)) {
bound(TPEN.userProjects)
}
} catch (_) {}
// Subscribe to future updates
const eventHandler = () => {
try {
bound(TPEN.userProjects)
} catch (_) {}
}
TPEN.eventDispatcher.on('tpen-user-projects-loaded', eventHandler)
// Trigger fetch if not already cached and not currently fetching
if (!TPEN.userProjects && !isFetching) {
isFetching = true
const token = TPEN.getAuthorization()
if (token) {
TPEN.getUserProjects(token)
.catch((error) => {
console.error("Failed to load user projects:", error)
})
.finally(() => { isFetching = false })
} else {
isFetching = false
}
}
return () => TPEN.eventDispatcher.off('tpen-user-projects-loaded', eventHandler)
}