Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # ~/plugins/apollo-schema.js
- import { login as loginMutation, me as meMutation } from '~/apollo/auth/login'
- export default class ApolloScheme {
- constructor(auth, options) {
- this.$auth = auth
- this.$apollo = auth.ctx.app.apolloProvider.defaultClient
- this.$apolloHelpers = auth.ctx.app.$apolloHelpers
- this.options = options
- }
- async login({ credentials }) {
- try {
- const user = await this.loginUser(credentials)
- if (user) {
- this.setUser(user)
- }
- } catch (error) {}
- }
- async loginUser(credentials) {
- try {
- const { data } = await this.$apollo.mutate({
- mutation: loginMutation,
- variables: credentials,
- })
- return Promise.resolve(data.login)
- } catch (error) {
- this.logout()
- return Promise.reject(error)
- }
- }
- setUser(user) {
- this.$auth.setUser(user)
- }
- async fetchUser() {
- try {
- const { data } = await this.$apollo.mutate({
- mutation: meMutation,
- })
- this.setUser(data.me)
- } catch (error) {
- this.logout()
- return Promise.reject(error)
- }
- }
- logout() {
- this.$auth.logout()
- }
- }
- # nuxt.config.js
- auth: {
- redirect: {
- logout: '/auth/login',
- login: '/auth/login',
- callback: '/auth/login',
- home: '/',
- },
- strategies: {
- apollo: {
- scheme: '~/plugins/apollo-schema.js',
- name: 'apollo',
- provider: 'apollo',
- default: true,
- },
- },
- },
- # ~/plugins/apollo.js
- import { HttpLink } from 'apollo-link-http'
- import { setContext } from 'apollo-link-context'
- import { from } from 'apollo-link'
- import { InMemoryCache } from 'apollo-cache-inmemory'
- export default ({ app, store }) => {
- const { baseGQL } = app.context.env
- const headersConfig = setContext(() => ({
- headers: {
- 'x-xsrf-token': app.$cookies.get('XSRF-TOKEN'),
- },
- credentials: 'include',
- }))
- const httpLink = new HttpLink({
- uri: baseGQL,
- })
- const link = from([headersConfig, httpLink])
- const cache = new InMemoryCache()
- return {
- link,
- cache,
- defaultHttpLink: false,
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement