quasarframework / app-extension-apollo Goto Github PK
View Code? Open in Web Editor NEWThe official Quasar App-Extension for Apollo and GraphQL - Currently Beta!
Home Page: https://quasar.dev
The official Quasar App-Extension for Apollo and GraphQL - Currently Beta!
Home Page: https://quasar.dev
Please add SSR support to the apollo as well, especially the state restoration.
Probably it requries to control possibility to add inject: false
to the createRenderer
method in dev-server
and production server.
I am attempting to build a pwa with quasar using GRAPHQL_URI=<my-ep> quasar build -m pwa
. However, when running quasar serve
from the pwa directory, the graphql requests keep defaulting to the local URI process.env.GRAPHQL_URI || 'http://127.0.0.1:1323/graph'
I am using the v2 branch of app-extension-apollo and am a little new to Vue so I might just be doing something silly here but I saw in the docs this was the way to build the app with environment variables for the graphgql endpoint
Hello,
I have a front-end application that should be deployed on-premises in different customers, hence it needs different API URLs for every customer. Also, this front-end application is deployed using a docker image. So far, every time that I want to update a customer, I have to build the front-end application with this command adjusted to every customer: GRAPHQL_URI=https://prod.customer1.com/graphql quasar build. So I end up having a docker image per customer. What I really want is just to have one single docker image and in the moment of instantiating a container, somehow set the graphql URI for that customer.
The only idea that I have is to put a config.json file in the public folder of the quasar app and from there fetch it and extract the URI per customer. In this way, every time that I instantiate a docker container, I set the config.json file with the URI for that customer.
The problem that I'm facing is that in order to consume that config.json, the API call is asynchronous and it's not working in this way.
public/config.json
{
"GRAPHQL_URI": "https://prod.example.com/graphql/v2"
}
src/apollo/apollo-client-config.js
export default async function (/* { app, router, store, ssrContext, urlPath, redirect } */) {
let GRAPHQL_URI
if (process.env.DEV) {
const config = await fetch('config.json').then(response => response.json())
GRAPHQL_URI = config.GRAPHQL_URI
}
return {
default: {
// 'apollo-link-http' config
// https://www.apollographql.com/docs/link/links/http/#options
httpLinkConfig: {
// you can define the 'uri' here or using an env variable when
// running quasar commands, for example:
// `GRAPHQL_URI=https://prod.example.com/graphql quasar build`
// `GRAPHQL_URI=https://dev.example.com/graphql quasar dev`
uri: process.env.GRAPHQL_URI || GRAPHQL_URI || 'http://localhost:5000/api'
},
// 'apollo-cache-inmemory' config
// https://www.apollographql.com/docs/react/caching/cache-configuration/#configuring-the-cache
cacheConfig: {},
// additional config for apollo client
// https://github.com/apollographql/apollo-client/blob/version-2.6/docs/source/api/apollo-client.mdx#optional-fields
additionalConfig: {}
},
// you can add more options or override the default config for a specific
// quasar mode or for dev and prod modes. Examples:
// ssr: {},
// dev: {
// httpLinkConfig: {
// uri: process.env.GRAPHQL_URI || 'http://dev.example.com/graphql'
// }
// },
// prod: {
// httpLinkConfig: {
// uri: process.env.GRAPHQL_URI || 'http://prod.example.com/graphql'
// }
// },
// the following gets merged to the config only when using ssr and on server
ssrOnServer: {
additionalConfig: {
// https://apollo.vuejs.org/guide/ssr.html#create-apollo-client
ssrMode: true
}
},
// the following gets merged to the config only when using ssr and on client
ssrOnClient: {
additionalConfig: {
// https://apollo.vuejs.org/guide/ssr.html#create-apollo-client
ssrForceFetchDelay: 100
}
}
}
}
I 'm tryng using lib..
package.json
{
"name": "app",
"version": "0.0.1",
"description": "A Quasar Project",
"productName": "Quasar App",
"author": "",
"private": true,
"scripts": {
"test": "echo \"No test specified\" && exit 0"
},
"dependencies": {
"@quasar/extras": "^1.0.0",
"axios": "^0.21.1",
"pinia": "^2.0.11",
"quasar": "^2.6.0",
"vue": "^3.0.0",
"vue-i18n": "^9.0.0",
"vue-router": "^4.0.0"
},
"devDependencies": {
"@intlify/vite-plugin-vue-i18n": "^3.3.1",
"@quasar/app-vite": "^1.0.0",
"@quasar/quasar-app-extension-apollo": "^2.0.0-beta.5",
"autoprefixer": "^10.4.2"
},
"engines": {
"node": "^18 || ^16 || ^14.19",
"npm": ">= 6.13.4",
"yarn": ">= 1.21.1"
}
}
src/pollo.js
import { createHttpLink, InMemoryCache } from '@apollo/client/core'
import { LocalStorage} from "quasar";
export /* async */ function getClientOptions(/* {app, router, ...} */ options) {
return Object.assign(
// General options.
{
link: createHttpLink({
uri:
process.env.GRAPHQL_URI ||
'http://172.20.0.94:8080/v1/graphql',
}),
cache: new InMemoryCache(),
},
process.env.MODE === 'spa'
? {
}
: {},
process.env.MODE === 'ssr'
? {
//
}
: {},
process.env.MODE === 'pwa'
? {
//
}
: {},
process.env.MODE === 'bex'
? {
//
}
: {},
process.env.MODE === 'cordova'
? {
//
}
: {},
process.env.MODE === 'capacitor'
? {
//
}
: {},
process.env.MODE === 'electron'
? {
//
}
: {},
// dev/prod options.
process.env.DEV
? {
//
}
: {},
process.env.PROD
? {
//
}
: {},
// For ssr mode, when on server.
process.env.MODE === 'ssr' && process.env.SERVER
? {
ssrMode: true,
}
: {},
// For ssr mode, when on client.
process.env.MODE === 'ssr' && process.env.CLIENT
? {
ssrForceFetchDelay: 100,
}
: {}
)
}
src/boot/apollo.js
import { ApolloClient /*, createHttpLink */ } from '@apollo/client/core'
import { ApolloClients } from '@vue/apollo-composable'
import { boot } from 'quasar/wrappers'
import { getClientOptions } from 'src/apollo'
export default boot(
/* async */ ({ app,store }) => {
// Default client.
const options = /* await */ getClientOptions(/*{app, router }*/)
const apolloClient = new ApolloClient(options)
const apolloClients = {
default: apolloClient,
}
app.provide(ApolloClients, apolloClients)
store.use(() => ({
$apollo: apolloClient
}))
}
)
apollo.config.js
'use strict'
/* eslint-env node */
// See https://www.apollographql.com/docs/devtools/apollo-config/
module.exports = {
client: {
service: {
name: 'default',
url: 'http://localhost:3000/graphql',
},
// Files processed by the extension
includes: ['src/**/*.vue', 'src/**/*.js', 'src/**/*.ts'],
},
}
quasar.config.js SECTION BOOT
boot: [
'i18n',
'axios',
'visual',
'apollo.js',
],`
component
<script setup>
import { ref } from 'vue'
const slide = ref('inicio')
import { useMutation } from '@vue/apollo-composable'
import gql from 'graphql-tag'
const username = ref('')
const password = ref('')
const variables= {
username: "master",
password: "dev"
}
async function login () {
const { mutate: userLogin } = useMutation(gql`
mutation userLogin($username: String!, $password: String!) {
userLogin(username: $username,password: $password) {
id
username
token
refresh
}
}
`,
{ variables: variables},
);
await userLogin()
}
</script>
I get error
The extension is checking for @quasar/app:
api.compatibleWith('@quasar/app', '>=3.0.0-beta.8 <4.0.0')
This condition needs to be changed to accommodate for @quasar/app-vite.
module.exports = function (api) {
// Quasar compatibility check.
api.compatibleWith('quasar', '>=2.0.0-beta.8 <3.0.0')
if (api.hasVite === true) {
api.compatibleWith('@quasar/app-vite', '^1.0.0')
}
else {
api.compatibleWith('@quasar/app', '>=3.0.0-beta.8 <4.0.0')
}
// Render templates in the app.
if (api.prompts.typescript) {
api.render('./templates')
} else {
api.render('../lib/templates')
}
api.extendJsonFile('.vscode/extensions.json', {
recommendations: ['apollographql.vscode-apollo'],
})
}
I have just migrated to Quasar v2 (Vue 3) with Vite integration and in the process of upgrading this extension I had to adjust my approach to importing my queries/mutations from dedicated files as such:
import gql from 'graphql-tag'
const FetchCurrentUser = gql`
query FetchCurrentUser {
currentUser @client {
id
name
phone
email
title
role {
id
name
}
}
}
`;
export { FetchCurrentUser }
While this approach is currently functional, the Apollo v3 migration docs recommend that all references to 'graphql-tag' be replaced with the new '@apollo/client' package since it has included graphql-tag as as dependency. The problem is that using import gql from '@apollo/client'
results In bundling errors due to Vite's rollup attempting and failing to reference non-existent 'react' packages. I also unsuccessfully attempted to exclude the react from the rollup using:
rollupOptions: {
external: ['react'],
},
Any thoughts on what the correct approach should be?
As a user, I want to be able to also install a simple GraphQL server to get quick feedback on how to work with Quasar and Apollo/GraphQL. The server should have some basic schema and resolvers, in order to facilitate issue: #29
Scott
Hey, just to make the documentation a little more clear for anyone else who is having the Apollo client with id default not found error, perhaps we could add after this line:
The extension will add a configuration file into src/apollo and a boot file. You'll need to manually register the latter into quasar.conf.js > boot.
Something like this:
If you are running into any issues with "id default not found", make sure you have edited your quasar.config.js to add "apollo.ts" (or .js) to the "boot" section.
For example: boot: ['apollo.ts']
I saw in your MR (#41) that you mention the Apollo client and provider hooks could be used for creating multiple clients, but I do not see how they could be used.
I am reading the official docs but I just don't see how I could utilize them.
Any pointers or a tiny sample code? Thanks!
Hi
I am using 2.0.0-beta.3 version and I wonder is there a simple way to update apolloClient
options.
Particularly, I have onAuthStateChanges
firebase listener placed in vuex
action and from there I would like to update authorization
header option.
Thanks
$ quasar dev
Dev mode.......... spa
Pkg quasar........ v2.0.0-beta.5
Pkg @quasar/app... v3.0.0-beta.7
Debugging......... enabled
Configured browser support (at least 87.91% of global marketshare):
· Chrome for Android >= 88
· Firefox for Android >= 83
· Android >= 81
· Chrome >= 78
· Edge >= 85
· Firefox >= 76
· iOS >= 10.3
· Opera >= 68
· Safari >= 11
App · Running "@quasar/apollo" Quasar App Extension...
App · ⚠️ Extension(@quasar/apollo): is not compatible with quasar v2.0.0-beta.5. Required version: ^1.5.1
Trying to install this extension to fresh quasar application throws the following error
yarn run v1.22.19
$ /home/pk/Projects/atlas-frontend/node_modules/.bin/quasar ext add @quasar/apollo@next
App • Installing "@quasar/apollo" Quasar App Extension
App • Installing @quasar/quasar-app-extension-apollo@next...
App • [sync] Running "yarn add --dev @quasar/quasar-app-extension-apollo@next" in /home/pk/Projects/atlas-frontend
[1/5] Validating package.json...
[2/5] Resolving packages...
[3/5] Fetching packages...
[4/5] Linking dependencies...
warning "@quasar/app-vite > [email protected]" has unmet peer dependency "rollup@^2.0.0".
warning " > [email protected]" has unmet peer dependency "postcss@^8.1.0".
[5/5] Building fresh packages...
success Saved lockfile.
success Saved 20 new dependencies.
info Direct dependencies
└─ @quasar/[email protected]
info All dependencies
├─ @apollo/[email protected]
├─ @graphql-typed-document-node/[email protected]
├─ @quasar/[email protected]
├─ @vue/[email protected]
├─ @wry/[email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
└─ [email protected]
? Does your app have typescript support? Yes
App • Updating /quasar.extensions.json for "@quasar/apollo" extension ...
App • Running App Extension install script...
App • ⚠️ Extension(@quasar/apollo): Dependency not found - @quasar/app. Please install it.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
The package.json
devDependency entry for quasar when using vite is the following "@quasar/app-vite": "^1.0.0",
Hello,
i am getting "Error: Apollo client with id default not found. Use provideApolloClient() if you are outside of a component setup
" when i make use of extension inside q-dialog (modal) component.
I have made sure that my apollo boot file is register in quasar.conf.js, and any other needed config and the extension works perfectly outside of q-dialog.
I temporarily had to recreate a whole client inside the component,
import { ApolloClient , createHttpLink, InMemoryCache } from '@apollo/client/core'
import { provideApolloClient} from '@vue/apollo-composable'
const apolloClient = new ApolloClient({
link: createHttpLink({
uri:'http://localhost:5000/graphql',
}),
cache: new InMemoryCache(),
})
provideApolloClient(apolloClient);
export default {
name: ...
but it doesn't seem like an optimal solution.
any other ideas to fix this?
thanks in advance
As a user, when I am adding the Apollo AE, I should be asked if I want to use either the somewhat simplified configuration of Apollo Boost, or if I want to use the full config of a regular Apollo installation.
As a user, I may want (and probably will want) some sort of environment setup, so my confidential data for GraphQL APIs (i.e. tokens or whatever is needed to access the API) isn't uploaded to my repository. Quasar offers two app extensions (AE) for this purpose. I should be asked if either one should be installed. The Apollo AE is only installing the extension as a proxy for the user. The env AEs should not be dependencies of the Apollo AE.
Scott
I finally made the switch to Quasar 2, and in SSR mode, I'm stuck in an infinite loop whenever I add similar queries to components that are loading simultaneously, e.g.
MainLayout.vue
query MainLayoutCurrentUser {
currentUser {
id
role
}
}
MainHeader.vue
query MainHeaderCurrentUser {
currentUser {
id
}
}
It's blazing fast when I load just one of those queries, or if I disable SSR entirely, but otherwise, it's stuck forever.
Other fixes I've tried:
I'm really at a loss here as to how to fix it. The only similar issue was a Vue 2 problem that was supposedly fixed in vuejs/apollo#1241
Any ideas?
Hey -- thanks for doing this app extension, it's really great to have!
I'm using a back-end site which gives hasura+postgres as a service (NHost.io, highly recommended). They have a very nice authentication system as well.
So my question is that I have to set the Authorization: Bearer
header. I can set it in the apollo-client-config.js
file, and that works, but then I (apparently) have to force a refresh of the page when someone logs in or out, to force a rebuild of the Apollo client.
Is there a better way to change the headers sent, past configuration time? I'd like to do it then anyway, because I feel like if the sign-in is slow, it may cause a race condition and the apollo-client-config.js
code will run before I can get the bearer token, since the sign-in is async.
Thanks for any help!
I want to create new apollo client and add it to existing apollo provider, but i can’t
What I try:
modify apollo-client-config.js, adding to default section additionalConfig
saw instruction for multiple clients https://apollo.vuejs.org/guide/multiple-clients.html
Without this new extension I can create ApolloProvider manually and add ApolloClients, but here I noticed, that apollo.js register only one 'defaultClient' ApolloClient.
const apolloProvider = new VueApollo({ defaultClient: apolloClient })
Extension(@quasar/apollo): is not compatible with @quasar/app v2.0.0. Required version: ^1.1.0
I am unable to get a Quasar app running after installing this extension; it fails with the above error during compilation. I get the same error whether I try from a Windows 10 PowerShell prompt or an Amazon Cloud9 (Ubuntu) prompt, so I doubt that the environment has anything to do with the problem. The problem occurs whether the GraphQL server is running or not. The error message is so generic that I have no idea where to look to try to troubleshoot the problem. (One oddity is that the compilation step reports two errors, but only one error message is displayed.)
Steps:
quasar create
:? Project name (internal usage for dev) apollo-graphql-demo
? Project product name (must start with letter if building mobile apps) Apollo GraphQL Demo
? Project description Apollo GraphQL Demo
? Author ....
? Pick your favorite CSS preprocessor: (can be changed later) SCSS
? Pick a Quasar components & directives import strategy: (can be changed later) Auto import
? Check the features needed for your project: ESLint (recommended), Axios
? Pick an ESLint preset: Prettier
? Continue to install project dependencies after the project has been created? (recommended) NPM
If I try to start the app at this point with quasar dev
, everything works fine.
? GraphQL endpoint URI (You can skip it now and set it later) http://localhost:3500
If I try to run the app now, I get the aforementioned error:
Dev mode.......... spa
Pkg quasar........ v1.12.8
Pkg @quasar/app... v2.0.1
Debugging......... enabled
Configured browser support (at least 84.46% of global marketshare):
· Chrome for Android >= 81
· Firefox for Android >= 68
· Android >= 81
· Chrome >= 73
· Edge >= 79
· Firefox >= 69
· iOS >= 10.0-10.2
· Opera >= 64
· Safari >= 10.1
App · Running "@quasar/apollo" Quasar App Extension...
App · Reading quasar.conf.js
App · Checking listening address availability (0.0.0.0:8080)...
App · Extension(@quasar/apollo): Extending quasar.conf...
App · Transpiling JS (Babel active)
App · Extending SPA Webpack config
App · Generating Webpack entry point
App · Booting up...
• Compiling:
└── SPA ████████████████████ 100% done in 4519 ms
ERROR Failed to compile with 2 errors 1:22:11 PM
error
Template execution failed: TypeError: Cannot read property 'mode' of undefined
error
Windows version info:
PS ....\demo> [System.Environment]::OSVersion.Version
Major Minor Build Revision
----- ----- ----- --------
10 0 18362 0
AWS Cloud9 environment info:
....:~/environment/demo (master) $ cat /etc/os-release
NAME="Amazon Linux AMI"
VERSION="2018.03"
ID="amzn"
ID_LIKE="rhel fedora"
VERSION_ID="2018.03"
PRETTY_NAME="Amazon Linux AMI 2018.03"
ANSI_COLOR="0;33"
CPE_NAME="cpe:/o:amazon:linux:2018.03:ga"
HOME_URL="http://aws.amazon.com/amazon-linux-ami/"
....:~/environment/demo (master) $ uname -r
4.14.181-108.257.amzn1.x86_64
on this repo
I'm trying to call this.$apollo.mutate
to run a mutation from this file
but all I'm getting is the error below
Uncaught TypeError: Cannot read properties of undefined (reading 'mutate')
at Proxy.sendLoginRequest (LoginPage.vue?62cc:43:1)
at callWithErrorHandling (runtime-core.esm-bundler.js?f781:155:1)
at callWithAsyncErrorHandling (runtime-core.esm-bundler.js?f781:164:1)
at emit$1 (runtime-core.esm-bundler.js?f781:720:1)
at eval (runtime-core.esm-bundler.js?f781:7292:1)
at onClick (QBtn.js?9c40:148:1)
at callWithErrorHandling (runtime-core.esm-bundler.js?f781:155:1)
at callWithAsyncErrorHandling (runtime-core.esm-bundler.js?f781:164:1)
at HTMLButtonElement.invoker (runtime-dom.esm-bundler.js?9cec:369:1)
I already checked quasar.config.js, src/apollo/index.js and src/boot/apollo.js. All of them should be set properly, and Yet I still have this issue
Any help is much appreciated
Since I won't have time to integrate this shortly, here are some random drafts about how you could use this package to support subscriptions via Websockets
When instantiating apolloClient
there is an option called tokenName
, as seen at e.g. this page. Previously I've used the option in another project which uses vue-apollo
directly, and it seems to work exactly as advertized, i.e. it will always set the authorization
header of every request with the token stored under a key named tokenName
from LocalStorage. However, when I try to set it in apollo-client-hooks.js
with e.g.
export async function apolloClientBeforeCreate({ apolloClientConfigObj }) {
apolloClientConfigObj.tokenName = "name";
}
no authorization header seems to be added to the request sent via apollo. In the end I managed to make it work by manually modifying the link and adding the authorization header to it. I wonder what the issue could be. I'm not sure if I'm missing something obvious here or if I misunderstood the option.
Hi! Please help me. How extend ApolloClient config and set custom request headers?
My current solution not working. In apollo-client-hooks.js
export function apolloClientBeforeCreate({ apolloClientConfigObj }) {
// if needed you can modify here the config object used for apollo client
// instantiation
const httpLink = createUploadLink({
uri: API_URI
});
const wsLink = new WebSocketLink({
options: {
connectionParams: {
Authorization: getToken()
},
reconnect: true
},
uri: WS_URI
});
const authMiddleware = new ApolloLink((operation, forward) => {
operation.setContext({
headers: {
Authorization: getToken()
}
});
return forward(operation);
});
const combinedLinks = split(
({ query }) => {
const { kind, operation } = getMainDefinition(query);
return kind === 'OperationDefinition' && operation === 'subscription';
},
wsLink,
httpLink
);
const errorLink = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors) {
graphQLErrors.map(({ message }) => {
console.error(`Unexpected error: ${message}`);
return message;
});
}
if (networkError) {
console.error(`Network Error: ${networkError}`);
}
});
apolloClientConfigObj = {
...apolloClientConfigObj,
link: ApolloLink.from([errorLink, concat(authMiddleware, combinedLinks)])
};
apolloClientConfigObj.cache.writeData({
data: {
...state
}
});
}
Hey, I found this repo on github, but it is not listed on the official app extensions page.
Is this official, incubating, or deprecated? Thanks!
In files of src/graphql/create-apollo-client[-ssr].js
we have following lines:
// create apollo client link
const link = new HttpLink(cfg.httpLinkConfig);
How to override it with this one?
const link = new WebSocketLink({
uri: process.env.API_GRAPHQL_WSS_URI,
options: {
reconnect: true,
timeout: 30000,
connectionParams: getConnectionParams(app.identity) // Boot-file related function.
}
});
Where getConnectionParams
is another function, returns callback () => Promise<ConnectionParams>
. It must be available in developer's project boot file or other place to override connectionParams.
Connection params is coming from this source:
import type { ConnectionParams } from 'subscriptions-transport-ws';
Inspired by this tutorial and turned into this home-made:
import { boot } from 'quasar/wrappers';
import VueApollo from 'vue-apollo';
// import ApolloSSR from 'vue-apollo/ssr';
import ApolloClient from 'apollo-client';
import { WebSocketLink } from 'apollo-link-ws';
import { InMemoryCache } from 'apollo-cache-inmemory';
import type { ConnectionParams } from 'subscriptions-transport-ws';
import type { IdentityManager } from 'boot/identity';
type Headers = {
authorization?: string;
}
// Custom configuration for wss using Bearer
//
function getConnectionParams(identity: IdentityManager): () => Promise<ConnectionParams>
{
return async () =>
{
const headers: Headers = {};
const accessToken = await identity.getAccessTokenAsync();
if (accessToken)
headers.authorization = `Bearer ${accessToken}`;
return { headers };
};
}
export default boot(({ Vue, app /*, ssrContext */ }) =>
{
Vue.use(VueApollo);
const link = new WebSocketLink({
uri: process.env.GRAPHQL_WSS_URI,
options: {
reconnect: true,
timeout: 30000,
connectionParams: getConnectionParams(app.identity)
}
});
const client = new ApolloClient({
link,
cache: new InMemoryCache({ addTypename: true })
});
const provider = new VueApollo({
defaultClient: client
});
app.apolloProvider = provider;
// Not possible to set ssrContext.rendered and ssrContext.apolloState with TypeScript!
// There is no module augmentation for internal QSsrContext in 'node_modules/@quasar/app/types/ssr.d.ts
});
Hi!
I was able to enable Apollo subscriptions with the help of the instructions in #37 but for the HTTP/WS link split the options in apollo-client-config are ignored and have to be recreated in the link definition.
Can this be made native maybe, like if a WS config is found, also create the wsLink in create-apollo-client.js and utilize the config in quasar-extension.json and apollo-client-config.js?
Hello,
after I solved the Problem to run GraphQL with Quasar, now the next problem jumping in my face. Anytime if I reload the page the first result of the graphql request is undefined and with 2nd request i get the result. This is weird and I dont find any solution for this. I hope u can help me with this.
How I send the request(initToken isn't empty)
I hope u can help me with this weird problem
Greetings
Subsonic
By using Apollo, even with Vue, the use of the apollo-cache is now often preferred on Vuex.
We have at least two ways to make it available from the router:
1 - replace Vuex by ApolloClient,
2 - add ApolloClient as a second store to be passed to the router and boot files.
The first choice asks to choose between Vuex and ApolloClient.
The second choice requires a small modification of the Quasar kernel.
Could we please update apollo-link
to the latest version 1.2.14
to resolve this issue?
apollographql/apollo-link#1261
As the latest version has the fix
graphql/graphql-js#2490
My current workaround is to install the latest apollo-link
myself.
However, I would imagine other running into this error and wasting time to figure it out.
Hi.
Quasar noobie here.
Just installed the framework, created a fresh project and ran quasar ext add @quasar/apollo
.
It throws the following error after asking me to enter my graphql endpoint:
? GraphQL endpoint URI (You can skip it now and set it later) http://api.example.com
App · Updating /quasar.extensions.json for "@quasar/apollo" extension ...
(node:33480) UnhandledPromiseRejectionWarning: ReferenceError: api is not defined
- install.js:5 Object.<anonymous>
[quasar]/[@quasar]/quasar-app-extension-apollo/src/install.js:5:1
- loader.js:1138 Module._compile
internal/modules/cjs/loader.js:1138:30
- loader.js:1158 Object.Module._extensions..js
internal/modules/cjs/loader.js:1158:10
- loader.js:986 Module.load
internal/modules/cjs/loader.js:986:32
- loader.js:879 Function.Module._load
internal/modules/cjs/loader.js:879:14
- loader.js:1026 Module.require
internal/modules/cjs/loader.js:1026:19
- helpers.js:72 require
internal/modules/cjs/helpers.js:72:18
- Extension.js:320 Extension.__getScript
[quasar]/[@quasar]/app/lib/app-extension/Extension.js:320:12
- Extension.js:324 Extension.__runInstallScript
[quasar]/[@quasar]/app/lib/app-extension/Extension.js:324:25
- Extension.js:182 Extension.install
[quasar]/[@quasar]/app/lib/app-extension/Extension.js:182:30
Hi there, I'm using Parse, which offers a sessionToken on login/signup. I store that sessionToken in a cookie.
When Quasar starts, I'd like it to
I tried doing that in a boot file, but it may be too early - I'm getting apolloClient is undefined.
In the javascript debugger console, the console.log(app)
below shows a default client at temp1.apolloProvider.defaultClient
.
Am I too early?
Thank you!
const auth = { /* async functions to make graphql mutations for signup, signin, and reestablishSession */}
// Add to Vue prototpye for reference in components
export default async ({ app, ssrContext, Vue }) => {
// Get cookies if in ssr mode (see: https://quasar.dev/quasar-plugins/cookies#Notes-on-SSR)
auth.cookies = process.env.SERVER
? Cookies.parseSSR(ssrContext)
: Cookies // otherwise we're on client
// Add $auth to all Vue components
Vue.prototype.$auth = auth
// Attempt to re-establish previous session using cookie
try {
console.log(app)
await auth.reestablishSession({ apolloClient: app.apolloProvider.defaultClient })
} catch(e) {
console.log(e) // EXCEPTION THROWN HERE: TypeError: Cannot read property 'defaultClient' of undefined
// Server did not accept session cookie (or transport error).
// auth.clearSessionToken()
}
return auth
}
The extension should probably support the Composition API of Vue Apollo, such as useQuery
, useMutation
etc.
https://v4.apollo.vuejs.org/api/use-query.html
I realize this is still only in alpha, so this issue is mostly for tracking.
Describe the bug
App • Running "@quasar/apollo" Quasar App Extension...
App •
error Command failed with exit code 1.
Hi, just curious if Websocket Support for Subscriptions will be or could be added?
In my case, this is currently for interacting with Hasura subscriptions.
I could work on this and PR, since I've already done this on an extension of my own.
I'd rather merge it here so I can simply use the official extension and drop my extension.
Let me know, thanks!
Hello, I didn't know where to report so I guess I will do it on both repository.
@quasar/apollo extension has trouble using @quasar/dotenv variables when in quasar.extensions.json,
dotenv is configured before apollo. It adds some quotation marks around the variable causing issues on the GRAPHQL_URI.
changing the order fixes the problem but still very ennoying issue and difficult to debug.
Hello, I recently started trying the extension with ssr and unless I am doing something horribly wrong, it seems that the data are rendered twice. Once prefetched by the server, and again instead of using data from the server, the client also fetch data and renders it after the server render. So we end up with duplicate data.
I started a new quasar project, added the extension and fetch data from graphql countries
using smart queries. No custom addition
quasar: "1.13.2"
quasar/app: "2.0.9",
quasar-app-extension-apollo: "1.0.0-beta.6"
As a user, I'd like to have the option to have a more advanced GraphQL server installed via the AE. This is a nice to have and isn't required for v1.0.
Examples of more advanced servers are Prisma and Yoga.
Scott
Instead of ssrForceFetchDelay
hack I really want to suggest you to include:
if (!process.env.SERVER) {
// It is a hack to solve issues of ssrForceFetchDelay, see App.mounted to see where it's enabling back the network fetches
apolloProvider.defaultClient.disableNetworkFetches = true
}
before apolloProvider will be resolved in the boot.
Then somewhere in the App.vue in mounted must be included the following code:
mounted () {
if (!process.env.SERVER) {
this.$apolloProvider.defaultClient.disableNetworkFetches = false
}
}
That one will prevent from the issue when dehydration goes too late, and HTML code not connected to the Vue.
So this code should be removed at all:
More on this issue is you can read here: apollographql/apollo-client#4814
Hello again, is it possible to add an option to choose the boot order ? At the moment the extension boot is added using push putting it after the boot files defined in quasar configuration. If there were an option to choose whether to unshift or push the boot file, it would help. Specifically when using a router-auth boot file to determine if the user is logged in at each route navigation.
Hi, is there a way to use Quasar V2 with apollo-vue Option API and Component API?
Thanks in advance
Hello,
is it possible to access the apolloClient inside a boot file. I tried accessing it via app.apolloProvider inside one of my boot files but at the time the boot file gets loaded the app.apolloProvider prop does not seem to be initialized. Is it possible to change the boot order of the plugin so I can access it?
A query using inline fragments gives the
You are using the simple (heuristic) fragment matcher, but your queries contain union or interface types. Apollo Client will not be able to accurately map fragments. To make this error go away, use the
IntrospectionFragmentMatcher
as described in the docs: https://www.apollographql.com/docs/react/advanced/fragments.html#fragment-matcher
According to the documentation on Using fragments with unions and interfaces this issue should be approached by informing the client of possible types to expect from a query. However, after doing so the above error persist and the client is unable to perform queries which feature inline fragments.
Example query within the ApolloQuery component:
<ApolloQuery
:query="gql => gql`${this.query}`"
:variables="{ ep: this.$route.params.id }"
>
<template v-slot="{ result: { loading, error, data } }">
<!-- Loading -->
<div v-if="loading" class="loading apollo">Loading...</div>
<!-- Error -->
<div v-else-if="error" class="error apollo">An error occurred</div>
<!-- Result -->
<div v-else-if="data">{{ data }}</div>
<!-- No result -->
<div v-else class="no-result apollo">No result :(</div>
</template>
</ApolloQuery>
Example query with inline fragment (used with this.query
above)
query HeroForEpisode($ep: Episode!) {
hero(episode: $ep) {
name
... on Droid {
primaryFunction
}
}
}
apollo.client.config.js
where the in memory cache configuration for possibleTypes should be applied:
// 'apollo-cache-inmemory' config
// https://www.apollographql.com/docs/react/caching/cache-configuration/#configuring-the-cache
cacheConfig: {
possibleTypes: {
Character: ["Droid"],
},
},
I think you just drop connectToDevTools: true
into apollo-client-config.js
but that doesn't match the Apollo DevTools documentation which says to put it into the ApolloClient
constructor.
Please when will this extention be ready for use??
STILL IN DEVELOPMENT??
Specify what's left so we can complete it
As a user, I would like to have an example app to learn from. The basic GraphQL server option will have a backend ready for this example app. See issue: #28
What that app does and what data is on the server, is up to whomever decides to take on this challenge.
One thing that should be used is Apollo's local state system. That should also be clearly demonstrated as an alternative to Vuex.
Scott
The method of building and deploying dist/ssr (copy, yarn install, yarn start) gives 500 error but works if quasar project root node_modules folder is present.
Also, .graphql files pointed in src are unavailable in dist folder.
I suspect I'm missing something, but I'm struggling to find the equivalent of the apolloClientBeforeCreate function from 1.0 in the v2 branch. Have those hooks been maintained? Thanks!
We need to add "vue-apollo"
in tsconfig.json
when working with typescript
:
{
"compilerOptions": {
"types": ["quasar", "vue-apollo"]
}
}
followed the steps in https://github.com/quasarframework/app-extension-apollo/tree/v2 to install Apollo extension to Quasar 2.4.9:
"devDependencies": {
"@babel/eslint-parser": "^7.13.14",
"@quasar/app": "^3.0.0",
"@quasar/quasar-app-extension-apollo": "^2.0.0-beta.3",
"eslint": "^7.14.0",
"eslint-config-prettier": "^8.1.0",
"eslint-plugin-vue": "^7.0.0",
"eslint-webpack-plugin": "^2.4.0"
},
found two files generated which are related to apollo:
I also manually created apollo.provider.js under the root directory with :
// apollo.config.js
module.exports = {
client: {
service: {
name: "my-app",
// URL to the GraphQL API
url: "http://localhost:4000/graphql",
},
// Files processed by the extension
includes: ["src/**/*.vue", "src/**/*.js"],
},
};
in my Vue file, I have the following code:
<script>
import { useQuery } from "@vue/apollo-composable";
import gql from "graphql-tag";
export default {
setup() {
const { result } = useQuery(gql`
query GetAllBooks {
getAllBooks {
id
name
}
}
`);
},
...
However, running this code led to the following error:
index.esm.js?0df5:48 Uncaught (in promise) Error: Apollo client with id default not found. Use provideApolloClient() if you are outside of a component setup.
at resolveClient (index.esm.js?0df5:48:1)
at start (index.esm.js?0df5:277:1)
at immediate (index.esm.js?0df5:493:1)
at callWithErrorHandling (runtime-core.esm-bundler.js?9e79:6737:1)
at callWithAsyncErrorHandling (runtime-core.esm-bundler.js?9e79:6746:1)
at job (runtime-core.esm-bundler.js?9e79:7154:1)
at doWatch (runtime-core.esm-bundler.js?9e79:7199:1)
at watch (runtime-core.esm-bundler.js?9e79:7040:1)
at useQueryImpl (index.esm.js?0df5:491:1)
at useQuery (index.esm.js?0df5:228:1)
Any idea which part's wrong?
I found this post I am using vue 3 with apollo/client but getting an error, seems Ricky Vadala's also using Quasar and following the same steps. However, the following doesn't work for me:
import { apolloClients } from 'src/extensions/apollo/boot'
as 'src/extensions/apollo/boot' does not exist.
Also, I cannot find your-app\node_modules@quasar\quasar-app-extension-apollo\README.md. Maybe Ricky Vadala was using an older version?
Please kindly shed some light on this. Surprisingly I cannot find an example of Quasar 2 + Apollo from the Internet.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.