Skip to content

Instantly share code, notes, and snippets.

@davidwebca
Created December 4, 2023 15:11
Show Gist options
  • Save davidwebca/d94c1d0762c2f8e9149fbab690a96870 to your computer and use it in GitHub Desktop.
Save davidwebca/d94c1d0762c2f8e9149fbab690a96870 to your computer and use it in GitHub Desktop.
Get GraphQL data automatically based on Nuxt/Vue component's name
import { getCurrentInstance } from 'vue';
export async function useAutoGraphql(vars = {}, options = {}) {
let cwd = null;
if (process.server) {
cwd = useState('___cwd', () => process.cwd());
} else {
cwd = useState('___cwd');
}
const inst = getCurrentInstance();
let gqlContent = null;
const filePath = `./${inst.type.__file.replace(cwd.value, 'queries').replace(/^\//, '').replace('.vue', '.gql')}`;
if (process.server) {
const theQuery = await import(/* @vite-ignore */filePath);
gqlContent = useState(filePath, () => theQuery.default.loc.source.body);
} else {
gqlContent = useState(filePath);
}
return useFetch('https://vocatio.ca/api', {
method: 'post',
body: {
query: gqlContent.value,
variables: vars,
},
...options,
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment