### Initializing Client with Composition API (Vue) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/setup.mdx Demonstrates how to use the `useClient` composition function within a Vue component's ` ``` -------------------------------- ### Installing Villus GraphQL Client Source: https://github.com/logaretm/villus/blob/main/README.md Provides commands to install the villus and graphql packages using yarn or npm. These are required dependencies for using the client. ```bash yarn add villus graphql # or npm npm install villus graphql --save ``` -------------------------------- ### Installing @villus/multipart Plugin (Bash) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/plugins/multipart.mdx Instructions for adding the @villus/multipart package to your project dependencies using yarn or npm. ```bash yarn add @villus/multipart # Or npm install @villus/multipart ``` -------------------------------- ### Install Villus via Yarn Source: https://github.com/logaretm/villus/blob/main/packages/villus/README.md Command to install the Villus library and its peer dependency 'graphql' using the Yarn package manager. ```Bash yarn add villus graphql ``` -------------------------------- ### Using useQuery in Vue Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/api/use-query.mdx Demonstrates how to use the `useQuery` composable from Villus within a Vue 3 ` ``` -------------------------------- ### Install Villus via NPM Source: https://github.com/logaretm/villus/blob/main/packages/villus/README.md Command to install the Villus library and its peer dependency 'graphql' using the NPM package manager. ```Bash npm install villus graphql --save ``` -------------------------------- ### Installing the Villus Batch Plugin (Bash) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/plugins/batch.mdx Instructions on how to add the `@villus/batch` package to your project dependencies using either yarn or npm package managers. ```Bash yarn add @villus/batch # Or npm install @villus/batch ``` -------------------------------- ### Using useQuery with Options in Vue Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/api/use-query.mdx Demonstrates how to use the `useQuery` hook in a Vue 3 ` ``` -------------------------------- ### Initializing Client as Vue Plugin (JavaScript) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/setup.mdx Shows how to use the `createClient` function to create a villus client instance and then register it as a Vue plugin using `app.use()`. This makes the client available globally to the entire Vue application. ```javascript import { createClient } from 'villus'; import { createApp } from 'vue'; const app = createApp({...}); // Creates a villus client instance const client = createClient({ url: '/graphql', // your endpoint. }); // Makes the villus client available to your app app.use(client); ``` -------------------------------- ### Install villus with Npm (Shell) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/index.mdx Installs the villus and graphql packages using the Npm package manager. ```sh npm install villus graphql --save ``` -------------------------------- ### Install villus with Yarn (Shell) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/index.mdx Installs the villus and graphql packages using the Yarn package manager. ```sh yarn add villus graphql ``` -------------------------------- ### Initializing Villus Client with Cache Plugin (Vue) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/plugins/cache.mdx Demonstrates how to initialize the villus client in a Vue component's setup script, including the default cache and fetch plugins. ```javascript ``` -------------------------------- ### Using Villus useQuery with Vue Suspense Container - Vue Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/queries.mdx Provides an example of a parent component using the `Suspense` component to wrap a child component (`Listing.vue`) that utilizes an awaited `useQuery`. It shows how to define fallback content while the child component's async setup is pending. ```vue ``` -------------------------------- ### Configuring Villus Client with Batch Plugin (Vue) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/plugins/batch.mdx Demonstrates how to import the `batch` plugin from `@villus/batch` and add it to the `use` array when initializing the `villus` client using `useClient` in a Vue setup script. ```Vue ``` -------------------------------- ### Configuring Villus Client with Default Plugins (Vue) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/plugins.mdx Demonstrates how to initialize the villus client within a Vue component's setup script, explicitly including the `defaultPlugins` using the `use` option. This ensures the client uses the standard fetch, cache, and dedup functionalities. ```vue ``` -------------------------------- ### Registering onData Callback (Vue) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/queries.mdx Demonstrates how to register a callback function using the `onData` hook returned by `useQuery` in a Vue setup script. The callback is executed whenever new data is available from the query. ```vue ``` -------------------------------- ### Configuring Fetch Plugin with useClient (Vue) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/plugins/fetch.mdx This snippet demonstrates how to import the necessary functions from 'villus', create an instance of the fetch plugin with potential options, and then register this plugin with the villus client using the `useClient` composition function within a Vue component's setup script. ```Vue ``` -------------------------------- ### Using Multiple Clients with Composition API (Vue) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/setup.mdx Illustrates how to configure multiple villus clients within different components or contexts using the `useClient` composition function. This allows querying different GraphQL APIs within the same application by providing a separate client for each component subtree. ```vue ``` -------------------------------- ### Implementing File Upload Mutation with Villus (Vue) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/plugins/multipart.mdx Shows a complete example of a Vue component using Villus to perform a single file upload mutation, including template, script setup, mutation definition, and upload function. ```vue ``` -------------------------------- ### Defining Type-Safe Plugins with definePlugin (TypeScript) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/plugins.mdx Shows how to use the `definePlugin` helper in TypeScript to create type-safe villus plugins. Includes examples for a simple plugin and a plugin that accepts configuration, demonstrating automatic type inference for the operation context. ```typescript import { definePlugin } from 'villus'; // opContext will be automatically typed const myPlugin = definePlugin(({ opContext }) => { opContext.headers.Authorization = 'Bearer '; }); const myPluginWithConfig = (config: { prefix: string }) => { // opContext will be automatically typed return definePlugin(({ opContext }) => { // Add auth headers with configurable prefix opContext.headers.Authorization = `${config.prefix} `; }); }; ``` -------------------------------- ### Using onError as useQuery Option (Vue) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/queries.mdx Demonstrates an alternative way to register a single `onError` callback by providing it directly as an option within the `useQuery` function call in a Vue setup script. This is suitable when only one error handler is needed. ```vue ``` -------------------------------- ### Registering onError Callback (Vue) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/queries.mdx Shows how to register a callback function using the `onError` hook returned by `useQuery` in a Vue setup script. This callback is specifically triggered only when an error occurs during the query execution. ```vue ``` -------------------------------- ### Renaming useQuery onSuccess hook to onData (JavaScript) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/migrate.mdx For consistency across the library, the onSuccess option previously available on useQuery has been renamed to onData. Update your useQuery calls to use the new option name. ```js import { useQuery } from 'villus'; useQuery({ query: GetPostById, variables, onSuccess: data => console.log(data), onData: data => console.log(data), }); ``` -------------------------------- ### Configure Villus Client in Vue 3 Source: https://github.com/logaretm/villus/blob/main/packages/villus/README.md Demonstrates how to initialize the Villus client with the GraphQL endpoint URL using the `useClient` composition API hook in a Vue 3 component's setup script. ```Vue ``` -------------------------------- ### Modifying opContext in a Plugin (JavaScript) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/plugins.mdx Provides examples of how a plugin can modify the `opContext` object to add headers, change the request body, or dynamically alter the request URL before the fetch operation. ```JavaScript function myPlugin({ opContext, operation }) { // Add auth headers opContext.headers.Authorization = 'Bearer '; // Encode additional information in the body opContext.body = JSON.stringify({ query: operation.query, variables: operation.variables, mutationKey: 39933 }); // Change the URL dynamically opContext.url = '/other/graphql'; } ``` -------------------------------- ### Fetching Data with useQuery (String Query) - Vue Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/queries.mdx Demonstrates the basic usage of the `useQuery` composition function in a Vue component's ` ``` -------------------------------- ### Using Villus useQuery with Vue Suspense - Vue Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/queries.mdx Demonstrates how to integrate `useQuery` with Vue 3's `Suspense` component by using `await` before the `useQuery` call within a ` ``` -------------------------------- ### Configure villus Client in Vue (Vue) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/index.mdx Configures the villus GraphQL client with a specific URL using the useClient hook within a Vue 3 setup script. ```vue ``` -------------------------------- ### Adding Authorization Headers with a Plugin (JavaScript) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/plugins.mdx Provides a JavaScript example of a villus plugin that adds a common `Authorization` header to GraphQL operations. Demonstrates how to register this custom plugin alongside the default plugins when initializing the villus client using `useClient`. ```javascript function authPlugin({ opContext }) { opContext.headers.Authorization = 'Bearer '; } // later in your setup import { useClient, defaultPlugins } from 'villus'; useClient({ url: '/graphql', use: [authPlugin, ...defaultPlugins()], // add the auth plugin alongside the default plugins }); ``` -------------------------------- ### Basic useMutation Usage in Vue Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/api/use-mutation.mdx This snippet demonstrates how to import the `useMutation` function from 'villus', define a static GraphQL mutation string, and call `useMutation` with the string to obtain reactive `data` and the `execute` function within a Vue 3 ` ``` -------------------------------- ### Mapping Subscription Data with a Custom Function (Vue) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/subscriptions.mdx Demonstrates using the second argument of `useSubscription` as a mapper function to transform the incoming subscription data. The example extracts the `lastMessage` field from the result. ```Vue ``` -------------------------------- ### Implementing Persistent Cache with localStorage (JavaScript) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/plugins.mdx Illustrates how to create a custom villus plugin for persistent caching using `localStorage`. The plugin caches query results after they resolve and retrieves them before execution, terminating the operation if a cached result is found and the policy is `cache-first`. Includes the setup with `useClient`. ```javascript function localStorageCache({ afterQuery, useResult, operation }) { // avoid caching mutations or subscriptions, also avoid caching queries with `network-only` policy if (operation.type !== 'query' || operation.cachePolicy === 'network-only') { return; } // Set the cache result after query is resolved // Using the `operation.key` is very handy here, it is a unique value that identifies this operation // The key is calculated from the query itself and it's variables afterQuery(result => { localStorage.setItem(operation.key, result); }); // Get cached item const cachedResult = localStorage.getItem(operation.key); // if exists in cache, terminate with result if (cachedResult) { // The first argument of `useResult` is the final value of the operation // The second argument is optional, it allows the plugin to terminate the operation // and stop all other plugins from executing, the last plugin must terminate with `true` // Terminate operation only if the cache policy is cache-first return useResult(cachedResult, operation.cachePolicy === 'cache-first'); } } // later in your setup import { useClient, fetch } from 'villus'; useClient({ url: '/graphql', use: [localStorageCache, fetch()], // add the local storage plugin along with the fetch plugin }); ``` -------------------------------- ### Unregistering onData Callback (Vue) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/queries.mdx Explains how to unregister a previously registered `onData` callback in a Vue setup script. The `onData` function returns a stop function that, when called, removes the specific callback from execution. ```vue ``` -------------------------------- ### Mapping Subscription Data to a Boolean Value (Vue) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/subscriptions.mdx Provides another example of using the mapper function with `useSubscription` to transform the subscription result into a boolean value based on a condition, such as checking the length of an array. ```Vue ``` -------------------------------- ### Basic Villus Mutation in Vue Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/mutations.mdx Demonstrates the basic usage of the `useMutation` composable in Vue 3's ` ``` -------------------------------- ### Unregistering onError Callback (Vue) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/queries.mdx Explains how to unregister a previously registered `onError` callback in a Vue setup script. The `onError` function returns a stop function that, when called, removes the specific error callback from execution. ```vue ``` -------------------------------- ### Setting Default Cache Policy on Villus Client - Vue Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/queries.mdx Explains how to configure the default `cachePolicy` for all queries by setting the option when initializing the Villus client using `useClient`. This example sets the default policy to `network-only`. ```Vue ``` -------------------------------- ### Initializing villus Client with Dedup Plugin in Vue Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/plugins/dedup.mdx This code snippet demonstrates how to initialize the villus GraphQL client within a Vue component's setup script. It imports the necessary functions (`useClient`, `dedup`, `fetch`) and configures the client to use both the `dedup` and `fetch` plugins. Including `dedup()` in the `use` array enables the plugin's functionality to prevent duplicate pending queries. ```javascript ``` -------------------------------- ### Villus Plugin for Token Refresh (Vue) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/plugins.mdx Demonstrates creating a villus plugin within a Vue component's setup script to automatically update an authentication token from the 'access-token' header of the response after a query completes. It uses the `afterQuery` callback and accesses the `response` object. ```vue ``` -------------------------------- ### Updating useSubscription reducer signature (JavaScript) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/migrate.mdx The argument order for the useSubscription reducer function has been flipped in v3.0. The new signature receives the incoming data as the first argument and the previous reduced value as the second, improving TypeScript support and flexibility. ```js function reduceMessages(old, incoming) { function reduceMessages(incoming, old) { ``` -------------------------------- ### Passing Static Variables to useQuery - Vue Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/queries.mdx Explains how to provide variables to a GraphQL query using the `variables` option in `useQuery`. In this example, the variables object is static, meaning the query will not automatically refetch if the variable values change. Requires `villus`. ```Vue ``` -------------------------------- ### Using Paused Function with Variables Destructuring in Vue/Villus Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/queries.mdx A variation of the paused function example, this snippet shows how the function receives the current variables object as an argument, allowing for direct destructuring of properties like id to control refetching. ```Vue ``` -------------------------------- ### Villus Plugin for Global Error Handling (TypeScript) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/plugins.mdx Illustrates how to create a villus plugin in TypeScript to implement a global error handler. This example specifically reports 500-level HTTP errors and unknown errors to Sentry using the `afterQuery` callback and checking the response status or the error object. ```typescript import { captureException } from '@sentry/browser'; /** * Reports unknown errors to Sentry to avoid having to do that everywhere. */ const sentryReportPlugin = definePlugin(({ operation, afterQuery }) => { afterQuery(({ error }, { response }) => { // collect some information about the query that failed const operationContext = { query: operation.query, type: operation.type, variables: operation.variables, }; if ((response?.status || 200) >= 500) { captureException(error, { contexts: { info: { description: 'received 500 response code from API', }, operation: operationContext, }, }); } // Other kinds of error codes should be handled by the consuming component if (error && isUnknownError(error)) { captureException(error, { contexts: { operation: operationContext, }, }); } // Notify user about the error // ... }); }); ``` -------------------------------- ### Sequencing Queries with Paused Based on Another Query's Data in Vue/Villus Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/queries.mdx This example demonstrates how to use the paused option to sequence queries. The second query (Comments) is configured to wait until the data from the first query (Post) is available and contains a post property before automatically executing. ```Vue ``` -------------------------------- ### Disabling Automatic Refetch with Paused Function in Vue/Villus Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/queries.mdx This example uses the paused option in useQuery to conditionally disable automatic refetching. It takes a function that returns a boolean, preventing the query from running unless the id property exists in the reactive variables object. ```Vue ``` -------------------------------- ### Creating a Configurable Plugin (JavaScript) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/plugins.mdx Demonstrates how to use a higher-order function pattern to create a configurable plugin that accepts parameters (like `prefix`) and returns the actual plugin function. ```JavaScript function myPluginWithConfig({ prefix }) { return ({ opContext, operation }) => { // Add auth headers with configurable prefix opContext.headers.Authorization = `${prefix} `; }; } ``` -------------------------------- ### Setting up Villus Client Injection in Vue Test Utils Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/testing.mdx Shows how to use Vue Test Utils' global mounting options to provide the `villus` client instance to a component under test. This is necessary because unit tests typically don't mount the full application hierarchy and the component depends on the client being available via provide/inject. ```JavaScript import { createClient, VILLUS_CLIENT } from 'villus'; import { mount } from '@vue/test-utils'; import PostsList from '@/components/PostsList.vue'; test('it lists the blog posts', async () => { const wrapper = mount(PostsList, { global: { provide: { [VILLUS_CLIENT]: createClient({ url: 'http://test/graphql', }), }, }, }); // TODO: Write assertions }); ``` -------------------------------- ### Manually Creating Villus Client - JavaScript Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/api/client.mdx Illustrates how to manually create a villus client instance using `createClient` after importing it. This allows direct use of the core client methods like `executeQuery` and `executeMutation`. ```JavaScript import { createClient } from 'villus'; const client = createClient({ url: '/graphql', }); ``` -------------------------------- ### Configuring Villus Client with Multipart Plugin (Vue) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/plugins/multipart.mdx Demonstrates how to import and configure the @villus/multipart plugin with the Villus client, ensuring it is used before the fetch plugin. ```vue ``` -------------------------------- ### Fetching Data with useQuery (graphql-tag/loader) - Vue Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/queries.mdx Illustrates importing a GraphQL query file directly using `graphql-tag/loader` (typically configured in a build tool like webpack). The imported query is then passed to the `useQuery` function. Requires `villus` and appropriate build configuration. ```Vue ``` -------------------------------- ### Configuring Subscription Client with graphql-ws (Vue) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/subscriptions.mdx Demonstrates how to integrate `graphql-ws` with `villus` using the `handleSubscriptions` plugin and `useClient`. It shows how to create a subscription forwarder function that adheres to the observable spec. ```Vue ``` -------------------------------- ### Fetching Data with useQuery (graphql-tag) - Vue Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/queries.mdx Shows how to use `useQuery` with a GraphQL query processed by `graphql-tag`. This approach compiles the query string into an Abstract Syntax Tree (AST), which can be beneficial for tooling and validation. Requires `villus` and the `graphql-tag` library. ```Vue ``` -------------------------------- ### Creating Villus Client with createClient - JavaScript Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/api/client.mdx Demonstrates the basic usage of the `createClient` function to create a raw villus client instance. This client can be used independently without being tied to Vue components or composables. ```JavaScript const client = createClient({ // opts ... }); ``` -------------------------------- ### Executing Basic Subscription and Watching Data (Vue) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/subscriptions.mdx Shows how to use the `useSubscription` function to run a GraphQL subscription in a Vue component. It defines a subscription query and demonstrates handling incoming data and errors within the callback function. ```Vue ``` -------------------------------- ### Using onData as useQuery Option (TS) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/queries.mdx Demonstrates an alternative way to register a single `onData` callback by providing it directly as an option within the `useQuery` function call in TypeScript. This is useful when only one callback is needed. ```ts import { useQuery } from 'villus'; useQuery({ query: GetPostById, variables, onData: data => console.log(data), }); ``` -------------------------------- ### Configuring villus Subscriptions Plugin with graphql-ws (Vue) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/plugins/handle-subscriptions.mdx This snippet demonstrates how to set up the `handleSubscriptions` plugin in `villus` using the Vue Composition API. It shows how to create a `graphql-ws` client, define the subscription forwarder function required by the plugin, and add the configured plugin to the `villus` client's `use` array. Requires `villus` and `graphql-ws`. ```Vue ``` -------------------------------- ### Exporting Cache Plugin Instance (TypeScript) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/plugins/cache.mdx Shows how to export the cache plugin instance during client initialization to make it accessible for external use, such as clearing the cache. ```typescript import { useClient, cache, fetch } from 'villus'; export const cachePlugin = cache(); useClient({ use: [cachePlugin, fetch()], }); ``` -------------------------------- ### Creating Villus Client with useClient - JavaScript Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/api/client.mdx Shows how to use the `useClient` function to create a villus client intended for injection into Vue components via `useQuery`, `useMutation`, or `useSubscription`. It accepts the same options as `createClient`. ```JavaScript useClient({ // createClient() opts... }); ``` -------------------------------- ### Using Batched Queries with useQuery (Vue) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/plugins/batch.mdx Shows how multiple `useQuery` calls within nested components or the same component will automatically be batched into a single GraphQL request when the batch plugin is configured. ```Vue ``` -------------------------------- ### Executing GraphQL Query with executeQuery - JavaScript Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/api/client.mdx Shows how to execute a GraphQL query using the `executeQuery` method on a villus client instance. It demonstrates passing the query string and variables, and handling the response via a Promise. ```JavaScript import { createClient } from 'villus'; const client = createClient({ url: '/graphql', }); client .executeQuery({ query: 'your query', variables: { // any variables }, }) .then(response => { // process the response }); ``` -------------------------------- ### Fetch Data with useQuery in Vue 3 Source: https://github.com/logaretm/villus/blob/main/packages/villus/README.md Shows how to define a GraphQL query string and use the `useQuery` composition API hook to fetch data, making the result available in the component's template. ```Vue ``` -------------------------------- ### Vue Component Fetching Posts with Villus Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/testing.mdx Defines a Vue component that uses the `useQuery` hook from `villus` to fetch a list of posts and display their titles in an unordered list. It relies on the `villus` client being provided via injection. ```Vue ``` -------------------------------- ### Using Villus Client as Vue Plugin - JavaScript Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/api/client.mdx Explains how to register a villus client instance as a Vue plugin using `app.use()`. This makes the client available globally at the application level, similar to `useClient` but for the entire app. ```JavaScript import { createClient } from 'villus'; import { createApp } from 'vue'; const app = createApp({...}); const client = createClient({ url: '/graphql', // your endpoint. }); // Makes the villus client available to your app app.use(client); ``` -------------------------------- ### Writing Asynchronous Assertions with wait-for-expect Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/testing.mdx Demonstrates how to write assertions for components that perform asynchronous operations like data fetching. It uses the `wait-for-expect` library to repeatedly check for the expected DOM state until it is met or a timeout occurs, accommodating the non-deterministic nature of asynchronous tests. ```JavaScript import { createClient, VILLUS_CLIENT } from 'villus'; import { mount } from '@vue/test-utils'; import waitForExpect from 'wait-for-expect'; import PostsList from '@/components/PostsList.vue'; test('it lists the blog posts', async () => { const wrapper = mount(PostsList, { global: { provide: { [VILLUS_CLIENT]: createClient({ url: 'http://test/graphql', }), }, }, }); await waitForExpect(() => { expect(wrapper.findAll('li').length).toBeGreaterThan(0); }); }); ``` -------------------------------- ### Executing GraphQL Mutation with executeMutation - JavaScript Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/api/client.mdx Illustrates how to execute a GraphQL mutation using the `executeMutation` method on a villus client instance. It shows passing the mutation query and variables, and processing the response via a Promise. ```JavaScript import { createClient } from 'villus'; const client = createClient({ url: '/graphql', }); client .executeMutation({ query: 'your query', variables: { // any variables }, }) .then(response => { // process the response }); ``` -------------------------------- ### Defining Villus Client Plugin Types (TypeScript) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/plugins.mdx Provides the TypeScript type definitions for key concepts in the villus plugin system, including `OperationType`, `AfterQueryCallback`, `FetchOptions`, `AfterQueryContext`, and the central `ClientPluginContext` interface, which details the available properties and functions within a plugin's execution context. ```typescript type OperationType = 'query' | 'mutation' | 'subscription'; type AfterQueryCallback = (result: OperationResult) => void | Promise; interface FetchOptions extends RequestInit { url?: string; } interface AfterQueryContext { response?: ParsedResponse; // The fetch operation response except it contains a parsed `body` property } interface ClientPluginContext { useResult: (result: OperationResult, terminate?: boolean) => void; // used to signal that the plugin found a result for the operation afterQuery: (cb: AfterQueryCallback, ctx: AfterQueryContext) => void; // Registers a callback to do something after the query is finished and the pipeline is done operation: { query: DocumentNode | string; // The query/mutation to be executed variables: Record; // The query variables cachePolicy: CachePolicy; // The cache policy for this operation key: number; // a unique key to identify this operation (useful for cache) type: OperationType; // the operation type: `query` or `mutation` or `subscription` }; opContext: FetchOptions; // The current operation context, contains stuff like `headers`, `body` and `url` and other fetch options response?: ParsedResponse; // The fetch operation response except it contains a parsed `body` property } type ClientPlugin = ({ useResult, operation }: ClientPluginContext) => void | Promise; ``` -------------------------------- ### Registering Multiple onData Callbacks (TS) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/queries.mdx Shows how to register multiple callback functions for the `onData` hook in TypeScript. Each registered callback will be executed sequentially when new data is received. ```ts onData(data => { // Do one thing }); onData(data => { // Do another }); ``` -------------------------------- ### Terminating Plugin Execution with useResult (JavaScript) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/plugins.mdx Demonstrates how to use `useResult` with the second argument set to `true` to terminate the plugin pipeline, preventing subsequent plugins from executing. ```JavaScript useResult(response, true); // Stops all plugins after it ``` -------------------------------- ### Caching Query Results with afterQuery (JavaScript) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/plugins.mdx Shows how the `cache` plugin uses the `afterQuery` hook to cache the operation result after the query has finished and resolved. ```JavaScript function cachePlugin({ afterQuery, useResult, operation }) { // ... afterQuery(result => { // Set the cache result after query is resolved setCacheResult(operation, result); }); // ... } ``` -------------------------------- ### Manually Re-fetching Query with execute - Vue Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/queries.mdx Explains how to use the `execute` function returned by `useQuery` to manually trigger a refetch of the query. This is useful for scenarios where a refetch is needed based on user interaction or other non-variable-driven logic. Requires `villus`. ```Vue ``` -------------------------------- ### Displaying Fetching Indication with Villus useQuery - Vue Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/queries.mdx Explains how to use the `isFetching` boolean ref returned by `useQuery` to display a loading indicator in the UI. This ref automatically updates when the query is initially fetched or subsequently refetched. ```vue ``` -------------------------------- ### Executing Villus Subscription with Observable (JS) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/api/client.mdx Demonstrates how to set up a villus client to handle GraphQL subscriptions using the subscriptions-transport-ws library and execute a subscription query. The executeSubscription method returns an Observable that allows handling incoming data and errors asynchronously. ```js import { createClient, handleSubscriptions, defaultPlugins } from 'villus'; import { SubscriptionClient } from 'subscriptions-transport-ws'; const subscriptionClient = new SubscriptionClient('ws://localhost:4001/graphql', {}); const subscriptionForwarder = operation => subscriptionClient.request(operation); const client = createClient({ url: 'http://localhost:4000/graphql', use: [handleSubscriptions(subscriptionForwarder), ...defaultPlugins()], }); const observable = await client.executeSubscription({ query: 'your subscription query', variables: { // any variables }, }); observable.subscribe({ next(response) { // handle incoming data }, // eslint-disable-next-line error(err) { // Handle errors }, }); ``` -------------------------------- ### Passing Reactive Variables (ref) to useQuery - Vue Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/queries.mdx Demonstrates passing a reactive ref created with Vue's `ref` function as variables to `useQuery`. Similar to using `reactive`, changing the value of the ref will automatically cause the query to refetch with the updated variables. Requires `villus` and Vue's reactivity API. ```Vue ``` -------------------------------- ### Registering Multiple onError Callbacks (TS) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/queries.mdx Illustrates how to register multiple callback functions for the `onError` hook in TypeScript. Each registered callback will be executed sequentially when an error is encountered during the query. ```ts onError(error => { // Do one thing }); onError(error => { // Do another }); ``` -------------------------------- ### Using Ref Variables with Villus useQuery (Vue) Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/api/use-query.mdx Illustrates how to provide reactive variables to the `useQuery` hook using a Vue `ref` object. Similar to `reactive`, Villus watches the ref and triggers a re-fetch when the ref's value (the variables object) changes, providing another way to manage reactive query parameters. ```vue ``` -------------------------------- ### Using Typed Document Node with Villus Source: https://github.com/logaretm/villus/blob/main/docs/src/pages/guide/typescript-codgen.mdx Illustrates using the `TypedDocumentNode` generated by the GraphQL Code Generator's Typed Document Node plugin. This simplifies imports by providing both type information and the query document in a single object for `useQuery`. ```ts import { useQuery } from 'villus'; import { PostsDocument } from '@/graphql/Posts'; const { data } = useQuery({ query: PostsDocument, variables: { // variables are now typed as PostsQueryVariables }, }); data.value; // is now typed as PostsQuery type! ```