-
Notifications
You must be signed in to change notification settings - Fork 198
3. Usage
Lam Kieu edited this page Jul 26, 2019
·
1 revision
Once the setup is completed you have a successfully enabled vue-apollo
in your project. Checkout Official example and vue-apollo how to use vue-apollo
inside your application code
You have following methods for authentication available:
// set your graphql-token
this.$apolloHelpers.onLogin(token /* if not default you can pass in client as second argument, and you can set custom cookies attributes object as the third argument */)
// unset your graphql-token
this.$apolloHelpers.onLogout(/* if not default you can pass in client as second argument */)
// get your current token (we persist token in a cookie)
this.$apolloHelpers.getToken(/* you can provide named tokenName if not 'apollo-token' */)
Check out the full example
For permanent authorization tokens the setup just provide getAuth
function for each of your endpoint configurations:
apollo: {
clientConfigs: {
default: {
httpEndpoint: 'https://graphql.datocms.com',
getAuth: () => 'Bearer your_token_string'
},
}
},
methods:{
async onSubmit () {
const credentials = this.credentials
try {
const res = await this.$apollo.mutate({
mutation: authenticateUserGql,
variables: credentials
}).then(({data}) => data && data.authenticateUser)
await this.$apolloHelpers.onLogin(res.token)
} catch (e) {
console.error(e)
}
},
}
methods:{
async onLogout () {
await this.$apolloHelpers.onLogout()
},
}
// middleware/isAuth.js
export default function ({app, error}) {
const hasToken = !!app.$apolloHelpers.getToken()
if (!hasToken) {
error({errorCode:503, message:'You are not allowed to see this'})
}
}
export default {
actions: {
foo (store, payload) {
let client = this.app.apolloProvider.defaultClient
}
}
}
export default {
asyncData (context) {
let client = context.app.apolloProvider.defaultClient
}
}
export default {
nuxtServerInit (store, context) {
let client = context.app.apolloProvider.defaultClient
}
}
export default {
methods:{
foo(){
// receive the associated Apollo client
const client = this.$apollo.getClient()
// most likely you would call mutations like following:
this.$apollo.mutate({mutation, variables})
// but you could also call queries like this:
this.$apollo.query({query, variables})
.then(({ data }) => {
// do what you want with data
})
}
}
}
Once you get the client, you can access its methods and properties. See API Reference
export default {
apollo: {
foo: {
query: fooGql,
variables () {
return {
myVar: this.myVar
}
}
}
}
}
See vue-apollo documentation for more information on smart queries
apollo: {
clientConfigs: {
default: '~/apollo/client-configs/default.js'
},
includeNodeModules: true
}