From de21a3fcac80eb9639059748e0e420250a4d7df7 Mon Sep 17 00:00:00 2001 From: bryantgillespie Date: Wed, 4 Oct 2023 17:44:53 -0400 Subject: [PATCH] combine into one plugin with auth --- plugins/directus.ts | 38 ++++++++++++++++++++++++++++---------- plugins/preview.ts | 12 ------------ 2 files changed, 28 insertions(+), 22 deletions(-) delete mode 100644 plugins/preview.ts diff --git a/plugins/directus.ts b/plugins/directus.ts index 6c9433e1..7dd4f3e4 100644 --- a/plugins/directus.ts +++ b/plugins/directus.ts @@ -1,4 +1,5 @@ -import { aggregate, createDirectus, readItem, readItems, readSingleton, rest } from '@directus/sdk'; +import { aggregate, authentication, createDirectus, readItem, readItems, readSingleton, rest } from '@directus/sdk'; + import Queue from 'p-queue'; import type { Schema } from '~/types/schema'; @@ -6,18 +7,35 @@ const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); const queue = new Queue({ concurrency: 15, interval: 1000 }); -export default defineNuxtPlugin(() => { +export default defineNuxtPlugin((nuxtApp) => { + const route = useRoute(); const config = useRuntimeConfig(); + const { directusUrl } = config.public; - const directus = createDirectus(directusUrl).with( - rest({ - onRequest: async (request) => { - await queue.add(() => sleep(400)); - return request; - }, - }) - ); + const preview = route.query.preview && route.query.preview === 'true'; + const token = route.query.token as string | undefined; + + const directus = createDirectus(directusUrl) + .with( + rest({ + onRequest: async (request) => { + await queue.add(() => sleep(400)); + return request; + }, + }) + ) + .with(authentication()); + + if (token) { + directus.setToken(token); + } + + if (preview && token) { + nuxtApp.hook('page:finish', () => { + refreshNuxtData(); + }); + } return { provide: { directus, readItem, readItems, readSingleton, aggregate } }; }); diff --git a/plugins/preview.ts b/plugins/preview.ts deleted file mode 100644 index 45b94926..00000000 --- a/plugins/preview.ts +++ /dev/null @@ -1,12 +0,0 @@ -export default defineNuxtPlugin((nuxtApp) => { - const route = useRoute(); - const preview = route.query.preview && route.query.preview === 'true'; - - if (preview) { - nuxtApp.hook('page:finish', () => { - refreshNuxtData(); - }); - } - - return { provide: { preview } }; -});