Skip to content

Instantly share code, notes, and snippets.

@aldarund
Created September 22, 2018 19:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aldarund/ad3de6f73da5f3d520dcb6cbec1c65a3 to your computer and use it in GitHub Desktop.
Save aldarund/ad3de6f73da5f3d520dcb6cbec1c65a3 to your computer and use it in GitHub Desktop.
import TOKEN_AUTH from '~/graphql/mutation/tokenAuth.gql'
import GET_LOGGED_USER from '~/graphql/query/getLoggedUser.gql'
export default class ApolloScheme {
constructor(auth, options) {
this.$auth = auth
this.name = options._name
this.client = this.$auth.ctx.app.apolloProvider.clients.defaultClient
this.options = Object.assign({}, options)
}
mounted() {
this.$auth.syncToken(this.name)
return this.$auth.fetchUserOnce()
}
async login(endpoint) {
await this.logout()
const {
data: {
tokenAuth: { token }
}
} = await this.client.mutate({
mutation: TOKEN_AUTH,
variables: {
email: endpoint.data.email,
password: endpoint.data.password
}
})
this.$auth.setToken(this.name, token)
return this.fetchUser()
}
async fetchUser() {
if (!this.$auth.getToken('apollo')) {
return
}
try {
const {
data: { me }
} = await this.client.query({
query: GET_LOGGED_USER,
fetchPolicy: 'network-only'
})
this.$auth.setUser(me)
} catch (e) {
if (e.networkError.response.status === 401) {
this.logout()
}
}
}
async logout() {
return this.$auth.reset()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment