Last active
February 7, 2025 23:38
-
-
Save suhodolskiy/1af5795fc33ba079dfaaf348e1f9f1ca to your computer and use it in GitHub Desktop.
Villus Nuxt Plugin (SSR)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { defaultPlugins, useClient } from 'villus' | |
| import { authPlugin } from './auth' | |
| import { ssrPlugin } from './ssr' | |
| export default defineNuxtPlugin((nuxtApp) => { | |
| const config = useRuntimeConfig() | |
| nuxtApp.hook('vue:setup', () => { | |
| useClient({ | |
| url: import.meta.server ? config.apiUrl : config.public.apiUrl, | |
| use: [authPlugin(), ssrPlugin(), ...defaultPlugins()], | |
| }) | |
| }) | |
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import type { | |
| ClientPlugin, | |
| ClientPluginContext, | |
| ClientPluginOperation, | |
| OperationResult, | |
| } from 'villus' | |
| interface StateSSR { | |
| [k: string]: OperationResult | undefined | |
| } | |
| export const ssrPlugin = (): ClientPlugin => { | |
| const state = useState<StateSSR>('__VILLUS__', () => ({})) | |
| const getState = (ctx: ClientPluginOperation): OperationResult | undefined => | |
| state.value[ctx.key] | |
| const setState = (ctx: ClientPluginOperation, result: OperationResult) => | |
| (state.value[ctx.key] = result) | |
| const clearState = (ctx: ClientPluginOperation) => | |
| (state.value[ctx.key] = undefined) | |
| return ({ afterQuery, useResult, operation }: ClientPluginContext) => { | |
| if (operation.type !== 'query') { | |
| return | |
| } | |
| if (import.meta.server) { | |
| afterQuery((result) => { | |
| setState(operation, result) | |
| }) | |
| } | |
| if (import.meta.client) { | |
| const ssrState = getState(operation) | |
| if (ssrState) { | |
| clearState(operation) | |
| return useResult(ssrState, true) | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment