Giter VIP home page Giter VIP logo

villus's Introduction

villus

Villus is a finger-like structures in the small intestine. They help to absorb digested food.

A small and fast GraphQL client for **Vue.js**


You can also help this this project and my other projects by donating one time or by sponsoring.

Features

  • ๐Ÿ“ฆ Minimal: Its all you need to query GQL APIs
  • ๐Ÿฆ Tiny: Very small footprint
  • ๐Ÿ—„ Caching: Simple and convenient query caching by default
  • ๐Ÿ‘• TypeScript: Written in Typescript and Supports GraphQL TS tooling
  • ๐Ÿ–‡ Composable: Built for the Composition API
  • โšก๏ธ Suspense: Supports the <Suspense> API
  • ๐Ÿ”Œ Plugins: Use existing plugins and create custom ones

Why use this

GraphQL is just a simple HTTP request. This library is meant to be a tiny client without all the bells and whistles attached to Apollo and its ecosystem which subsequently means it is faster across the board due to it's smaller bundle size and reduced overhead. villus offers simple strategies to cache and batch, dedup your GraphQL requests.

villus also supports file uploads and subscriptions without compromising bundle size through plugins.

If you are looking for a more full-featured client use vue-apollo, it has everything you need.

You can read more about it in the announcement post.

Documentation

You can find the documentation here

Quick Start

First install villus:

yarn add villus graphql

# or npm

npm install villus graphql --save

Or because villus is so simple, you can use it via CDN:

<!-- Import Vue 3 -->
<script src="https://unpkg.com/[email protected]/dist/vue.global.js"></script>
<!-- Villus -->
<script src="https://unpkg.com/villus@latest/dist/villus.min.js"></script>

Usage

Configure the GraphQL client for your root component:

<script setup>
import { useClient } from 'villus';

useClient({
  url: 'http://localhost:3002/graphql',
});
</script>

Then you can use useQuery in any child component:

<template>
  <div>
    <div v-if="data">
      <pre>{{ data }}</pre>
    </div>
  </div>
</template>

<script setup>
import { useQuery } from 'villus';

const AllPosts = `
  query AllPosts {
    posts {
      title
    }
  }
`;

const { data } = useQuery({
  query: AllPosts,
});
</script>

villus makes frequent tasks such as re-fetching, caching, deduplication, mutations, and subscriptions a breeze. It has even built-in Suspense support with Vue 3! Consult the documentation for more use-cases and examples.

Compatibility

This library relies on the fetch web API to run queries, you can use unfetch (client-side) or node-fetch (server-side) to use as a polyfill.

This library is compatible with Vue 3.0+ or 2.7+

Examples

Live examples can be found here

License

MIT

villus's People

Contributors

altitudems avatar bitraten avatar bravik avatar callumacrae avatar connorshea avatar dalukasdev avatar danielfiniki avatar dependabot[bot] avatar fahdarafat avatar gavinxue avatar gilesbutler avatar imjasonmiller avatar jbaubree avatar logaretm avatar lrstanley avatar pipe01 avatar ppseafield avatar sibbng avatar thalesagapito avatar v3lop5 avatar zigomir avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

villus's Issues

@villus/batch causes uncaught exception in Promise

villus performs await fetch inside try ... catch block while batch does not. This causes uncaught promise exception.

Imo it would be nice if @villus/batch would also handle this case and return CombinedError.

Add response headers to afterQuery plugin function

First thanks a lot for this beautiful package.

My issue is that Im using Devise auth token as my JWT backend strategy. As a safety measure they change the token after each request and sent back the new token on a response header. So I need to get that header to update the token for the next request.

I currently have something like this. But the opContext.headers['access-token'] is using the request token not the response one. It would be nice to have access to the response properties (response opContext) in afterQuery.

function afterwareAuth({ afterQuery, opContext }: ClientPluginContext) {
  afterQuery(() => {
    console.log(opContext.headers)
    auth.setAuthStorageTokens({
      // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
      // @ts-ignore
      accessToken: opContext.headers['access-token'],
      // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
      // @ts-ignore
      client: opContext.headers.client,
      // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
      // @ts-ignore
      expiry: opContext.headers.expiry,
      // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
      // @ts-ignore
      uid: opContext.headers.uid
    })
  })
}

Thanks for you help!

Cannot detect villus client - useMutation

Great work on this project, super handy!

I've successfully got queries to work however I am having issues with mutations, I get the following error:
image

Here's my setup:

Use client within app.vue -
image

A typescript file that has a createProduct function -
image

Then, I am calling createProduct on button press from within a vue file.

Not sure what i'm doing wrong here but any pointers would be greatly appreciated!

CombinedError Object property graphqlErrors is undefined

It appears that the CombinedError Object does not set the graphqlErrors property:
grafik

The actual error is still accessible in the response > body > errors array

Expected behaviour would be that the graphqlErrors property of CombinedError holds a array of GraphQLError objects.

Set headers after client creation, or per request?

Hope this is not too much of an edge case:

Trying to use Villus in a Vuex store module in a Nuxt app.

This works, if I do not need to pass Authorization headers:

// myStoreModule.js
import { createClient } from 'villus'

const client = createClient({
  url: 'http://localhost:4000/graphql'
})
// ...
export const actions = {
  async fetchData({ commit, dispatch }) {
    const data = await client.executeQuery({
      query: BOARD_QUERY
    })
    commit('SET_BOARD', data)
  }
}

However, I do need to pass Authorization headers. But in the Vuex store, I can only access the original headers from the http.request object inside of actions. Therefore, I cannot do:

const client = createClient({
  url: 'http://localhost:4000/graphql',
  context: () => {
    return {
      fetchOptions: {
        headers: {
          Authorization: TOKEN
        }
      }
    };
  }
})

...because I do not have access to TOKEN outside of my actions.

Therefore, I would like to do something like this:

export const actions = {
  async fetchData({ commit, dispatch }, { req }) {
	// first get TOKEN from original request
    const token = getToken(req.headers)
	// the set the token to the previously created client
    client.context = () => {
      return {
        fetchOptions: {
          headers: {
            Authorization: TOKEN
          }
        }
      }
    }
	//...
}

But this does not work. So, how would you go around this issue?

With Axios, I could easily modify the headers on each request. Would something like that be possible with Villus client?

[Question] Query Batching is only on vue 3 ?

I use "villus": "^0.3.0" for vue 2 and query batching is not available.

In the doc, only suspend get the only for vue 3.x flag

Can we use the alpha version for vue 2 ?

Thanks !

updating UI after a mutation

How would you update the UI after a mutation? One of apollo's most useful features is that you return entities that you would like updated after mutation, and the UI is just magically updated. Is there a pattern for this using this library?

Registering client as a plugin

Hi, I'm using Vue 3. I want to install villus but I dont have a root component and don't want to use useClient on every component. Is installing villus as a plugin possible?

const app = createApp()

const client = createClient({ url: '...' });

app.use(client)

withProvider can't be found

I'm receiving the TS error: Module '"../node_modules/villus/dist/types/src"' has no exported member 'withProvider'.ts(2305). Is this still a function that I can use?
Re: https://logaretm.github.io/villus/guide/client.html#withprovider-function

I'm using yarn add -D villus@next.

import { createClient, withProvider } from "villus"
import App from "./App.vue"
import { createApp } from "vue"
import { routeGuard } from "./auth"
import { router } from "./router"

const client = createClient({
  url: "/api/1.0/graphql", // Your endpoint
})

const AppWithClient = withProvider(App, client)

createApp(AppWithClient).use(router).use(routeGuard, { router }).mount("#app")

Villius with vue 2

Hello, can we use villus in vue 2 without composition api ?

If yes, can you provide a example ?

Thanks !!

installing with vue 3

getting this peer dependency resolution error with vue 3.0.2 while installing 1.0.0-rc.4

npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/vue
npm ERR!   vue@"3.0.2" from the root project
npm ERR!   peer vue@"^2.0.0 || >=3.0.0-rc.0" from [email protected]
npm ERR!   node_modules/villus
npm ERR!     villus@"1.0.0-rc.4" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer vue@">= 2.5 < 3" from @vue/[email protected]
npm ERR! node_modules/@vue/composition-api
npm ERR!   peer @vue/composition-api@"^1.0.0-beta.1" from [email protected]
npm ERR!   node_modules/villus
npm ERR!     villus@"1.0.0-rc.4" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\shala\AppData\Local\npm-cache\eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\shala\AppData\Local\npm-cache\_logs\2020-11-06T20_49_00_684Z-debug.log

useSubscription does not support reactive variables

code like

    const variables = computed(() => ({
      limit: pageSize,
      offset: (state.pagination.current - 1) * pageSize,
    }));
    const { data, execute: queryOrders } = useSubscription({
      query: Orders,
      variables: variables,
    });

This is the websocket raw message

id: "4"
payload: {,โ€ฆ}
cachePolicy: "network-only"
key: 2582834560
query: "subscription ...."
type: "subscription"
variables: {_dirty: true, __v_isRef: true, __v_isReadonly: true}
type: "start"

ref variables properties is sent to server, not ref value.

[TypedDocumentNode] No auto complete on variable

Version : Beta 8

Can't seem to get auto complete to work on variables
image

image

Works fine for returned data
image

export const UserDocument: DocumentNode<UserQuery, UserQueryVariables> = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"user"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"where"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UserWhereUniqueInput"}}},"directives":[]}],"directives":[],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"where"},"value":{"kind":"Variable","name":{"kind":"Name","value":"where"}}}],"directives":[],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"email"},"arguments":[],"directives":[]},{"kind":"Field","name":{"kind":"Name","value":"id"},"arguments":[],"directives":[]}]}}]}}]};

Thanks for all your great work!

Question on cache-and-network policy

Greetings, thank you for the awesome library. Good job there ๐Ÿ‘๐Ÿผ.

Does cache-and-network update the reactive data returned by useQuery when network fetch is resolved?

Query Batching error [Wordpress graphql] [vue3]

Hello @logaretm I'm trying to use villus with vue 3 now.

I've got an error with batcher.

Without batcher the data is good, with the batcher i've got an error

Screen Shot 2020-07-29 at 12 12 03 PM

It's weird because, the data is here in the response, but villus throw an error.

You can test here : http://origin-wp.demotte.net/cms/graphql

import { computed } from 'vue'
import { useClient, batcher, useQuery } from 'villus'

useClient({
  url: 'http://origin-wp.demotte.net/cms/graphql/cms/graphql',
  fetch: batcher()
})
const { data, error, done } = useQuery({ query: computed(() => `{ allSettings { generalSettingsUrl } }`) })

If you remove fetch: batcher() it's ok

thanks !!!

How to add authorization headers to subscription?

This code doesn't work.

    const subscriptionClient = new SubscriptionClient(
      process.env.VUE_APP_GRAPHQL_WS_ENDPOINT,
      {
        reconnect: true,
        connectionParams: () => {
          return {
            Authorization: `Bearer ${token.access}`,
            // or headers: { Authorization: `Bearer ${token.access}` }
          };
        },
      }
    );

Feature request: Support for cache-only policy

I am showing a list that gets lazy loaded after an Intersection Observer is triggered. When a visitor navigates away from this list, but then hits the back button I would like to repopulate all data that already exists in the local cache. But if it doesnt exists in the cache yet, I would like to wait until the Intersection Observer is triggered before loading the data over the network again.

This policy doesnt seem to be supported yet, or do you prefer we track / fix this in userland?

Missing fetch method after Nuxt Apollo removal

Hi there; great package. I'm testing Villus with the nuxtjs/composition-api module.

Everything runs well until I completely remove the Apollo module; the following error is rendered:

Could not resolve a fetch() method, you should provide one.

Here is my Nuxt plugin config:

import Vue from 'vue'
import { onGlobalSetup } from '@nuxtjs/composition-api'
import { useClient } from 'villus'

Vue.use(useClient)

export default () => {
  onGlobalSetup(() => {
    useClient({
      url: process.env.BACKEND_URL || 'http://localhost:1337/graphql',
    })
  })
}

Here is index.vue:

<template>
  <div>
    <div v-if="data">
      <pre>{{ data }}</pre>
    </div>
  </div>
</template>

<script>
import { useQuery } from 'villus'

export default {
  data() {
    return {
      //
    }
  },
  setup() {
    // Using Strapi API
    const AllCards = `
      query AllCards {
        cards {
          id
          title
          description
          }
        }
    `
    const { data } = useQuery(AllCards)

    return {
      data,
    }
  },
}
</script>

Thanks again.

Canceling a request

We have a use-case that would require canceling requests - some are triggered explicitly using execute and some are triggered dynamically, by mutating responsive query variables.

Is there any way to do this with Villus? If not, how do you feel about such a feature, would you consider implementing it/accept a PR implementing it or do you think it's not a good fit for the automagic approach the library generally takes?

Allow direct use of client

Allowing the client to be provided to useQuery, useMutation, and useSubscription would allow the use of multiple clients in the same context, something not currently possible.

The api would look like this:

    const client = createClient({
      url: '/graphql' // your endpoint.
    });
    const { data } = useQuery({
      client,
      query: '{ todos { text } }'
    });

Ability to use subscriptions outside of component

I have a use-case where I need to wrap the useSubscription function in a class, that lies outside of a component scope. I was wondering if there is a way to handle unsubscribing to a subscription ? I can see that you handle it, in a component context, but it would be nice to have the ability to manually unsubscribing from a subscription.
Otherwise great lib!

Nuxt support?

This looks like a neat library! I want to get rid of vue-apollo because of all the cruft it comes with.

Will I be able to use this with Nuxt?

Client Schema Extension

Greetings. Is it possible to extend the schema in the client by providing local resolvers?

graphql error

I just followed the instructions on https://logaretm.com/blog/2020-01-11-announcing-villus/?utm_campaign=Vue.js%20News&utm_medium=email&utm_source=Revue%20newsletter but getting the errors;


    WARNING in ./node_modules/villus/dist/villus.esm.js 95:15-20
    export 'print' (imported as 'print') was not found in 'graphql' (possible exports: )
     @ ./node_modules/babel-loader/lib/index.js!./node_modules/vue-loader/dist/index.js??ruleSet[1].rules[9].use[0]!./src/frontend/frontend.vue?vue&type=script&lang=js 1:0-35 9:4-13
     @ ./src/frontend/frontend.vue?vue&type=script&lang=js 1:0-184 1:0-184 1:185-358 1:185-358
     @ ./src/frontend/frontend.vue 2:0-59 3:0-54 3:0-54 4:0-13 7:2-16 11:27-33 20:0-13 22:15-21
     @ ./src/frontend/frontend.js 2:0-33 12:10-13

    WARNING in ./node_modules/villus/dist/villus.esm.js 134:19-31
    export 'GraphQLError' (imported as 'GraphQLError') was not found in 'graphql' (possible exports: )
     @ ./node_modules/babel-loader/lib/index.js!./node_modules/vue-loader/dist/index.js??ruleSet[1].rules[9].use[0]!./src/frontend/frontend.vue?vue&type=script&lang=js 1:0-35 9:4-13
     @ ./src/frontend/frontend.vue?vue&type=script&lang=js 1:0-184 1:0-184 1:185-358 1:185-358
     @ ./src/frontend/frontend.vue 2:0-59 3:0-54 3:0-54 4:0-13 7:2-16 11:27-33 20:0-13 22:15-21
     @ ./src/frontend/frontend.js 2:0-33 12:10-13

    WARNING in ./node_modules/villus/dist/villus.esm.js 137:19-31
    export 'GraphQLError' (imported as 'GraphQLError') was not found in 'graphql' (possible exports: )
     @ ./node_modules/babel-loader/lib/index.js!./node_modules/vue-loader/dist/index.js??ruleSet[1].rules[9].use[0]!./src/frontend/frontend.vue?vue&type=script&lang=js 1:0-35 9:4-13
     @ ./src/frontend/frontend.vue?vue&type=script&lang=js 1:0-184 1:0-184 1:185-358 1:185-358
     @ ./src/frontend/frontend.vue 2:0-59 3:0-54 3:0-54 4:0-13 7:2-16 11:27-33 20:0-13 22:15-21
     @ ./src/frontend/frontend.js 2:0-33 12:10-13

    ERROR in ./node_modules/graphql/index.mjs 25:0-49
    Module not found: Error: Can't resolve './version' in 'D:\Coding\hypetraq\node_modules\graphql'
    Did you mean 'version.js'?
    BREAKING CHANGE: The request './version' failed to resolve only because it was resolved as fully specified
    (probably because the origin is a '*.mjs' file or a '*.js' file where the package.json contains '"type": "module"').
    The extension in the request is mandatory for it to be fully specified.
    Add the extension to the request.
     @ ./node_modules/villus/dist/villus.esm.js 6:0-46 95:15-20 134:19-31 137:19-31
     @ ./node_modules/babel-loader/lib/index.js!./node_modules/vue-loader/dist/index.js??ruleSet[1].rules[9].use[0]!./src/frontend/frontend.vue?vue&type=script&lang=js 1:0-35 9:4-13
     @ ./src/frontend/frontend.vue?vue&type=script&lang=js 1:0-184 1:0-184 1:185-358 1:185-358
     @ ./src/frontend/frontend.vue 2:0-59 3:0-54 3:0-54 4:0-13 7:2-16 11:27-33 20:0-13 22:15-21
     @ ./src/frontend/frontend.js 2:0-33 12:10-13

    ERROR in ./node_modules/graphql/index.mjs 27:0-49
    Module not found: Error: Can't resolve './graphql' in 'D:\Coding\hypetraq\node_modules\graphql'
    Did you mean 'graphql.js'?
    BREAKING CHANGE: The request './graphql' failed to resolve only because it was resolved as fully specified
    (probably because the origin is a '*.mjs' file or a '*.js' file where the package.json contains '"type": "module"').
    The extension in the request is mandatory for it to be fully specified.
    Add the extension to the request.
     @ ./node_modules/villus/dist/villus.esm.js 6:0-46 95:15-20 134:19-31 137:19-31
     @ ./node_modules/babel-loader/lib/index.js!./node_modules/vue-loader/dist/index.js??ruleSet[1].rules[9].use[0]!./src/frontend/frontend.vue?vue&type=script&lang=js 1:0-35 9:4-13
     @ ./src/frontend/frontend.vue?vue&type=script&lang=js 1:0-184 1:0-184 1:185-358 1:185-358
     @ ./src/frontend/frontend.vue 2:0-59 3:0-54 3:0-54 4:0-13 7:2-16 11:27-33 20:0-13 22:15-21
     @ ./src/frontend/frontend.js 2:0-33 12:10-13

    ERROR in ./node_modules/graphql/index.mjs 29:0-40:50
    Module not found: Error: Can't resolve './type' in 'D:\Coding\hypetraq\node_modules\graphql'
    Did you mean 'index.js'?
    BREAKING CHANGE: The request './type' failed to resolve only because it was resolved as fully specified
    (probably because the origin is a '*.mjs' file or a '*.js' file where the package.json contains '"type": "module"').
    The extension in the request is mandatory for it to be fully specified.
    Add the extension to the request.
     @ ./node_modules/villus/dist/villus.esm.js 6:0-46 95:15-20 134:19-31 137:19-31
     @ ./node_modules/babel-loader/lib/index.js!./node_modules/vue-loader/dist/index.js??ruleSet[1].rules[9].use[0]!./src/frontend/frontend.vue?vue&type=script&lang=js 1:0-35 9:4-13
     @ ./src/frontend/frontend.vue?vue&type=script&lang=js 1:0-184 1:0-184 1:185-358 1:185-358
     @ ./src/frontend/frontend.vue 2:0-59 3:0-54 3:0-54 4:0-13 7:2-16 11:27-33 20:0-13 22:15-21
     @ ./src/frontend/frontend.js 2:0-33 12:10-13

    ERROR in ./node_modules/graphql/index.mjs 42:0-48:205
    Module not found: Error: Can't resolve './language' in 'D:\Coding\hypetraq\node_modules\graphql'
    Did you mean 'index.js'?
    BREAKING CHANGE: The request './language' failed to resolve only because it was resolved as fully specified
    (probably because the origin is a '*.mjs' file or a '*.js' file where the package.json contains '"type": "module"').
    The extension in the request is mandatory for it to be fully specified.
    Add the extension to the request.
     @ ./node_modules/villus/dist/villus.esm.js 6:0-46 95:15-20 134:19-31 137:19-31
     @ ./node_modules/babel-loader/lib/index.js!./node_modules/vue-loader/dist/index.js??ruleSet[1].rules[9].use[0]!./src/frontend/frontend.vue?vue&type=script&lang=js 1:0-35 9:4-13
     @ ./src/frontend/frontend.vue?vue&type=script&lang=js 1:0-184 1:0-184 1:185-358 1:185-358
     @ ./src/frontend/frontend.vue 2:0-59 3:0-54 3:0-54 4:0-13 7:2-16 11:27-33 20:0-13 22:15-21
     @ ./src/frontend/frontend.js 2:0-33 12:10-13

    ERROR in ./node_modules/graphql/index.mjs 50:0-122
    Module not found: Error: Can't resolve './execution' in 'D:\Coding\hypetraq\node_modules\graphql'
    Did you mean 'index.js'?
    BREAKING CHANGE: The request './execution' failed to resolve only because it was resolved as fully specified
    (probably because the origin is a '*.mjs' file or a '*.js' file where the package.json contains '"type": "module"').
    The extension in the request is mandatory for it to be fully specified.
    Add the extension to the request.
     @ ./node_modules/villus/dist/villus.esm.js 6:0-46 95:15-20 134:19-31 137:19-31
     @ ./node_modules/babel-loader/lib/index.js!./node_modules/vue-loader/dist/index.js??ruleSet[1].rules[9].use[0]!./src/frontend/frontend.vue?vue&type=script&lang=js 1:0-35 9:4-13
     @ ./src/frontend/frontend.vue?vue&type=script&lang=js 1:0-184 1:0-184 1:185-358 1:185-358
     @ ./src/frontend/frontend.vue 2:0-59 3:0-54 3:0-54 4:0-13 7:2-16 11:27-33 20:0-13 22:15-21
     @ ./src/frontend/frontend.js 2:0-33 12:10-13

    ERROR in ./node_modules/graphql/index.mjs 51:0-68
    Module not found: Error: Can't resolve './subscription' in 'D:\Coding\hypetraq\node_modules\graphql'
    Did you mean 'index.js'?
    BREAKING CHANGE: The request './subscription' failed to resolve only because it was resolved as fully specified
    (probably because the origin is a '*.mjs' file or a '*.js' file where the package.json contains '"type": "module"').
    The extension in the request is mandatory for it to be fully specified.
    Add the extension to the request.
     @ ./node_modules/villus/dist/villus.esm.js 6:0-46 95:15-20 134:19-31 137:19-31
     @ ./node_modules/babel-loader/lib/index.js!./node_modules/vue-loader/dist/index.js??ruleSet[1].rules[9].use[0]!./src/frontend/frontend.vue?vue&type=script&lang=js 1:0-35 9:4-13
     @ ./src/frontend/frontend.vue?vue&type=script&lang=js 1:0-184 1:0-184 1:185-358 1:185-358
     @ ./src/frontend/frontend.vue 2:0-59 3:0-54 3:0-54 4:0-13 7:2-16 11:27-33 20:0-13 22:15-21
     @ ./src/frontend/frontend.js 2:0-33 12:10-13

    ERROR in ./node_modules/graphql/index.mjs 53:0-56:206
    Module not found: Error: Can't resolve './validation' in 'D:\Coding\hypetraq\node_modules\graphql'
    Did you mean 'index.js'?
    BREAKING CHANGE: The request './validation' failed to resolve only because it was resolved as fully specified
    (probably because the origin is a '*.mjs' file or a '*.js' file where the package.json contains '"type": "module"').
    The extension in the request is mandatory for it to be fully specified.
    Add the extension to the request.
     @ ./node_modules/villus/dist/villus.esm.js 6:0-46 95:15-20 134:19-31 137:19-31
     @ ./node_modules/babel-loader/lib/index.js!./node_modules/vue-loader/dist/index.js??ruleSet[1].rules[9].use[0]!./src/frontend/frontend.vue?vue&type=script&lang=js 1:0-35 9:4-13
     @ ./src/frontend/frontend.vue?vue&type=script&lang=js 1:0-184 1:0-184 1:185-358 1:185-358
     @ ./src/frontend/frontend.vue 2:0-59 3:0-54 3:0-54 4:0-13 7:2-16 11:27-33 20:0-13 22:15-21
     @ ./src/frontend/frontend.js 2:0-33 12:10-13

    ERROR in ./node_modules/graphql/index.mjs 58:0-91
    Module not found: Error: Can't resolve './error' in 'D:\Coding\hypetraq\node_modules\graphql'
    Did you mean 'index.js'?
    BREAKING CHANGE: The request './error' failed to resolve only because it was resolved as fully specified
    (probably because the origin is a '*.mjs' file or a '*.js' file where the package.json contains '"type": "module"').
    The extension in the request is mandatory for it to be fully specified.
    Add the extension to the request.
     @ ./node_modules/villus/dist/villus.esm.js 6:0-46 95:15-20 134:19-31 137:19-31
     @ ./node_modules/babel-loader/lib/index.js!./node_modules/vue-loader/dist/index.js??ruleSet[1].rules[9].use[0]!./src/frontend/frontend.vue?vue&type=script&lang=js 1:0-35 9:4-13
     @ ./src/frontend/frontend.vue?vue&type=script&lang=js 1:0-184 1:0-184 1:185-358 1:185-358
     @ ./src/frontend/frontend.vue 2:0-59 3:0-54 3:0-54 4:0-13 7:2-16 11:27-33 20:0-13 22:15-21
     @ ./src/frontend/frontend.js 2:0-33 12:10-13

    ERROR in ./node_modules/graphql/index.mjs 60:0-97:42
    Module not found: Error: Can't resolve './utilities' in 'D:\Coding\hypetraq\node_modules\graphql'
    Did you mean 'index.js'?
    BREAKING CHANGE: The request './utilities' failed to resolve only because it was resolved as fully specified
    (probably because the origin is a '*.mjs' file or a '*.js' file where the package.json contains '"type": "module"').
    The extension in the request is mandatory for it to be fully specified.
    Add the extension to the request.
     @ ./node_modules/villus/dist/villus.esm.js 6:0-46 95:15-20 134:19-31 137:19-31
     @ ./node_modules/babel-loader/lib/index.js!./node_modules/vue-loader/dist/index.js??ruleSet[1].rules[9].use[0]!./src/frontend/frontend.vue?vue&type=script&lang=js 1:0-35 9:4-13
     @ ./src/frontend/frontend.vue?vue&type=script&lang=js 1:0-184 1:0-184 1:185-358 1:185-358
     @ ./src/frontend/frontend.vue 2:0-59 3:0-54 3:0-54 4:0-13 7:2-16 11:27-33 20:0-13 22:15-21
     @ ./src/frontend/frontend.js 2:0-33 12:10-13

    webpack 5.4.0 compiled with 9 errors and 3 warnings in 6049 ms


anyone have an idea?

GraphQL Codegen Plugin Setup

What codegen plugins would be best to combine with Villus?

For example is it compatible with the output of @graphql-codegen/typescript-vue-apollo

clearing cache

how to manualy clear cache on logout when not using "network-only" mode?

Feature request: make error prefixes optional

Currently the prefixes [Network] and [GraphQL] is always added on errors, but I prefer to not have those prefixes as I use the error message directly on my forms. And then it looks weird that it says [GraphQL]: Some validation error returned by the API.

Provide operation information to context factory.

The current context factory api does not provide any information regarding the operation being executed.

This is a proposal to pass information on the current operation to the context factory. the revised api would look like this:

import { createClient } from 'villus';

const client = createClient({
  endpoint: '/graphql',
  context: (operation, variables) => {
    // possibly use the operation or variables to set headers
    return {
      fetchOptions: {
        headers: {
          Authorization: 'bearer TOKEN'
        }
      }
    };
  }
});

Use case: setting different headers depending on the query being executed. An alternative is allowing queries to set headers.

Fetching on focus

Would you consider adding a PR that implemented automatic refetching whenever was refocused?

Latest tag points to Vue3 version

The latest tag on npm points to 1.0.0-alpha.5, which is dependent on Vue3. This may cause confusion for those who are following the install instructions.

SSR support: missing cache state transfer/restore?

Hey, thanks for this awesome graphql client!

Was wondering whether it is supported to send the cache state after SSR to the client and restore the cache on hydration? The issue at the moment is that this happens:

  • Request SSR page A, fetch data from API
  • Navigate (client side) to page B
  • Hit back button to return to page A, data is again fetched because cache is still empty as previously the query was run on the server side.

Export VILLUS_CLIENT symbol

It could be useful to export the VILLUS_CLIENT symbol in order to access the provided client from other composable functions.

[Subscriptions] SubscriptionClient module not found, despite install.

Setup: Vite, Villus Beta 8

I've installed subscriptions-transport-ws but keep getting this error in chrome. Potentially could be related to the Vite build process.

image

<template>
  <img alt="Vue logo" src="./assets/logo.png" />
  <HelloWorld />
</template>

<script lang="ts">
import HelloWorld from "./components/HelloWorld.vue";
import { SubscriptionClient } from "subscriptions-transport-ws";
import { useClient, handleSubscriptions, defaultPlugins } from "villus";

const subscriptionClient = new SubscriptionClient(
  "ws://xxxxx/graphql",
  { reconnect: true },
);

const subscriptionForwarder = (operation: any) =>
  subscriptionClient.request(operation);

export default {
  name: "App",
  components: {
    HelloWorld,
  },
  setup() {
    useClient({
      url: "https://xxxxx/graphql",
      use: [handleSubscriptions(subscriptionForwarder), ...defaultPlugins()],
    });
  },
};
</script>

Best way to re-execute query

Hello, thanks for your great job :)

Small question, i want to re-excute a query when a variable change,

   const lang = _.capitalize(root.lang)

    const { data } = useQuery({
      query: `
      {
        pageBy(pageId: 30) {
          title
          slug
          acf_pages {
            metaDescription: meta${lang}Description
            metaTitle: meta${lang}Title,
            template: adminComponent
          }
        }
      }
      `,
    })

In this case lang change, what the best way to re-excute query ? watch lang and manually fetch the data ?

Thanks

[AFTER PATCH] Did you forget to call `useClient`?

Versions with Issue : Rc0 + Rc1

image

Issue happens when getReport() is called on change of a date. When getReport() is called during page load /setup it works fine.

Logic of program is when date input is changed, send useQuery to fetch data using the selected date.

App.VUE

<script lang="ts">
import { SubscriptionClient } from "subscriptions-transport-ws";
import { defineComponent, computed } from "vue";
import DesktopMenu from "./components/DesktopMenu.vue";
import { router } from "./main";
import { useClient } from "villus";

import { ActionTypes, MutationTypes, useStore } from "./store";

export default defineComponent({
  name: "Navigation",
  components: {
    DesktopMenu,
  },
  setup() {
    const store = useStore();

    useClient({
      url: "/graphql",
    });

  },
});
</script>

Home.VUE

<template>
  <div>
    Home
    <input v-model="datePage" type="date" />
    <p v-if="returnData">
      {{ returnData }}
    </p>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed, watchEffect } from "vue";
import { useQuery } from "villus";

import { CostDocument } from "../generated/graphql-operations";

export default defineComponent({
  name: "HelloWorld",
  setup() {
    const returnData = ref();
    const datePage = ref("2020-10-18");
    const formattedDate = computed(() =>
      datePage.value.toString().split("-").join(""),
    );

    const data = ref(null);
    watchEffect(async (datePage) => {
      async function getReport() {
        try {
          console.log("date value changed:", formattedDate);

          const { data, error } = await useQuery({
            query: CostDocument,
            variables: { date: formattedDate.value },
          });

          console.log("Query:", data, error);
          returnData.value = data;
        } catch (error) {
          console.log("error", error);
        }
      }
      data.value = await getReport();
    });

    return { returnData, datePage };
  },
});
</script>

Query Batching error [Wordpress graphql]

Hello i try to use query batching with worpdress graphql but i got a error CombinedError

When i don't use the batcher() i see 2 call with no error

Screen Shot 2020-04-13 at 11 34 56 AM

When i activate it

    useClient({
      url: '/cms/graphql',
      fetch: batcher()
    })

I see the call, the response seem to be good, an array of 2 objects

Screen Shot 2020-04-13 at 11 34 28 AM

But i get an error on each component response.

Screen Shot 2020-04-13 at 11 33 53 AM

Do you have an idea of who we can fix that ? A villius issue or wp-graphql issue ?

Thanks

Don't require query objects to have a loc property

I'm using GraphQL code generator with the typed document node plugin. This plugin exports an object that looks like Object { kind: "Document", definitions: (1) [โ€ฆ] }, which is an issue since here the normalizeQuery function expects the query object to have a loc property. This can be worked around by doing TheQueryDocument.loc = {}, so I think the requirement could be dropped altogether and instead check for a property like kind.

fetchOnMount missing from type definition

Looks like this was missed when refactoring lazy -> fetchOnMount

const { data, error, execute, isFetching } = useQuery<
      GetUsersQuery,
      GetUsersQueryVariables
    >({
      query: usersQuery,
      fetchOnMount: false,
    })
No overload matches this call.
  Overload 1 of 2, '(query: MaybeReactive<string | DocumentNode>, variables?: Exact<{ [key: string]: never; }> | Ref<Exact<{ [key: string]: never; }>> | undefined): ThenableQueryComposable<...>', gave the following error.
    Argument of type '{ query: DocumentNode; fetchOnMount: boolean; }' is not assignable to parameter of type 'MaybeReactive<string | DocumentNode>'.
      Object literal may only specify known properties, and 'query' does not exist in type 'DocumentNode | Ref<string | DocumentNode>'.
  Overload 2 of 2, '(query: QueryCompositeOptions<Exact<{ [key: string]: never; }>>): ThenableQueryComposable<GetUsersQuery>', gave the following error.
    Argument of type '{ query: DocumentNode; fetchOnMount: boolean; }' is not assignable to parameter of type 'QueryCompositeOptions<Exact<{ [key: string]: never; }>>'.
      Object literal may only specify known properties, and 'fetchOnMount' does not exist in type 'QueryCompositeOptions<Exact<{ [key: string]: never; }>>'.Vetur(2769)

Done value not updated with variables

Hello,

I watch the done value, but when variable change and the query is auto-refetch, done doesn't change anymore.

I can set done value to false

    watch(done, () => {
      if(done.value)
        done.value = false
    })

But i think it's not the best way :)

Cannot detect villus Client, did you forget to call `useClient`?

Hello, i get this error Cannot detect villus Client, did you forget to call useClient?

reproduction

<script setup>
import { useClient, useQuery } from 'villus'

useClient({
  url: "https://pet-library.moonhighway.com/",
})

export const { data } = useQuery({ query: `
  query AllPets ($category: PetCategory) {
    allPets (category: $category) { id }
  }
` })
</script>

When i use UseQuery in a child component, i don't have any error.

We cannot use useClient and useQuery in the same level anymore ?

The error come with the latest release.

Thanks !!

Update peerDependencies

[email protected]" has incorrect peer dependency "graphql@^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0".

GraphQL 15 should work just fine..

As for @vue/composition-api ... is this required with Vue 3 ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.