Skip to content

Instantly share code, notes, and snippets.

@tfoxy
Created April 18, 2018 00:11
Show Gist options
  • Select an option

  • Save tfoxy/03beda1d680a2644fb90cdcedacc8305 to your computer and use it in GitHub Desktop.

Select an option

Save tfoxy/03beda1d680a2644fb90cdcedacc8305 to your computer and use it in GitHub Desktop.
Patch VueApollo#prefetchQuery so that it works when calling `prefetchAll` on client
import { omit } from 'lodash';
import VueApollo from 'vue-apollo';
const VUE_APOLLO_QUERY_KEYWORDS = [
'variables',
'watch',
'update',
'result',
'error',
'loadingKey',
'watchLoading',
'skip',
'throttle',
'debounce',
'subscribeToMore',
'prefetch',
'manual',
];
VueApollo.prototype.prefetchQuery = prefetchQuery;
function prefetchQuery(queryOptions, context, client) {
let variables;
// Client
if (!client) {
client = this.defaultClient;
} else if (typeof client === 'string') {
client = this.clients[client];
if (!client) {
throw new Error(`[vue-apollo] Missing client '${client}' in 'apolloProvider'`);
}
}
// Simple query
if (!queryOptions.query) {
queryOptions = {
query: queryOptions,
}
} else {
const { prefetch } = queryOptions;
const prefetchType = typeof prefetch;
// Resolve variables
if (prefetchType !== 'undefined') {
let result;
if (prefetchType === 'function') {
result = prefetch(context);
} else {
result = prefetch;
}
if (!result) {
return Promise.resolve();
} else if (prefetchType === 'boolean') {
const optVariables = queryOptions.variables;
if (typeof optVariables !== 'undefined') {
// Reuse `variables` option with `prefetch: true`
if (typeof optVariables === 'function') {
variables = optVariables.call(context);
} else {
variables = optVariables;
}
} else {
variables = undefined;
}
} else {
variables = result;
}
}
}
// Query
if (typeof queryOptions.query === 'function') {
queryOptions.query = queryOptions.query(context);
}
return new Promise((resolve, reject) => {
const options = omit(queryOptions, VUE_APOLLO_QUERY_KEYWORDS);
options.variables = variables;
if (process.env.VUE_ENV === 'server') {
options.fetchPolicy = 'network-only';
}
client.query(options).then(resolve, reject);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment