Created
December 4, 2023 15:11
-
-
Save davidwebca/d94c1d0762c2f8e9149fbab690a96870 to your computer and use it in GitHub Desktop.
Get GraphQL data automatically based on Nuxt/Vue component's name
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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