-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathtv.ts
53 lines (38 loc) · 1.34 KB
/
tv.ts
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
import { authentication, createDirectus, rest } from '@directus/sdk';
import Queue from 'p-queue';
import type { Schema } from '~/types/schema';
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
const queue = new Queue({ intervalCap: 10, interval: 500, carryoverConcurrencyCount: true });
export default defineNuxtPlugin((nuxtApp) => {
const route = useRoute();
const config = useRuntimeConfig();
const { tvUrl } = config.public;
const preview = route.query.preview && route.query.preview === 'true';
const token = route.query.token as string | undefined;
const directusTv = createDirectus<Schema>(tvUrl as string, {
globals: {
// @ts-ignore
fetch: (...args) => queue.add(() => fetchRetry(0, ...args)),
},
})
.with(rest())
.with(authentication());
if (token) {
directusTv.setToken(token);
}
if (preview && token) {
nuxtApp.hook('page:finish', () => {
refreshNuxtData();
});
}
return { provide: { directusTv } };
});
async function fetchRetry(count: number, ...args: Parameters<typeof fetch>) {
const response = await fetch(...args);
if (count > 2 || response.status !== 429) return response;
// eslint-disable-next-line no-console
console.warn(`[429] Too Many Requests (Attempt ${count + 1})`);
// Try again after interval / 2
await sleep(500);
return fetchRetry(count + 1, ...args);
}