From bd7d02d86813b2ec5502cbe1cbdba2ed8839878c Mon Sep 17 00:00:00 2001 From: Julien Huang Date: Sat, 31 Aug 2024 20:41:20 +0200 Subject: [PATCH] feat: allow factory function for customClient (#219) * feat: allow factory function for customClient * docs: wording * chore: use runWithContext --- docs/content/2.guides/2.advanced/1.custom-client.md | 7 ++++++- src/runtime/plugin.ts | 6 ++++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/docs/content/2.guides/2.advanced/1.custom-client.md b/docs/content/2.guides/2.advanced/1.custom-client.md index 35dacfe..fc918a3 100644 --- a/docs/content/2.guides/2.advanced/1.custom-client.md +++ b/docs/content/2.guides/2.advanced/1.custom-client.md @@ -5,11 +5,16 @@ description: '' # Custom Client -You can make the module use your own [`@prismicio/client`](https://prismic.io/docs/technical-reference/prismicio-client?utm_campaign=devexp&utm_source=nuxt3doc&utm_medium=doc) instance. To do so, export it from `~/prismic/client` (`~/app/prismic/client` on Nuxt 3): +You can make the module use your own [`@prismicio/client`](https://prismic.io/docs/technical-reference/prismicio-client?utm_campaign=devexp&utm_source=nuxt3doc&utm_medium=doc) instance. To do so, export it from `~/prismic/client` (`~/app/prismic/client` on Nuxt 3), it can be either a factory function or the custom client: ```javascript [~/prismic/client.[jt]s] import { createClient } from '@prismicio/client' +export default () => { + // this will be run inside by a nuxt plugin. So you will have access to the nuxt instance inside of it. + return createClient('my-repository') +} + export default createClient('my-repository') ``` diff --git a/src/runtime/plugin.ts b/src/runtime/plugin.ts index 9611a7e..f631568 100644 --- a/src/runtime/plugin.ts +++ b/src/runtime/plugin.ts @@ -6,14 +6,16 @@ import NuxtLink from '#app/components/nuxt-link' import { defineNuxtPlugin, useCookie, useRequestEvent, onNuxtReady, refreshNuxtData, useHead, useRuntimeConfig, useRouter } from '#imports' // @ts-expect-error vfs cannot be resolved here -import client from '#build/prismic/proxy/client' +import _client from '#build/prismic/proxy/client' // @ts-expect-error vfs cannot be resolved here import linkResolver from '#build/prismic/proxy/linkResolver' // @ts-expect-error vfs cannot be resolved here import richTextSerializer from '#build/prismic/proxy/richTextSerializer' -export default defineNuxtPlugin((nuxtApp) => { +export default defineNuxtPlugin(async (nuxtApp) => { const options: PrismicModuleOptions = useRuntimeConfig().public.prismic + const client = typeof _client === 'function' ? await nuxtApp.runWithContext(() => _client()) : _client + const endpoint = options.environment || options.endpoint || (client as Client | undefined)?.endpoint || '' const prismicPlugin = createPrismic({