Created
September 22, 2018 19:27
-
-
Save aldarund/ad3de6f73da5f3d520dcb6cbec1c65a3 to your computer and use it in GitHub Desktop.
This file contains 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 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