Home

Issue: 1043

How to use a plugin inside my store ?

[issue link]

Hi all,

I cannot figure it out how can I access to my plugin inside my store (if it’s possible).

What the initial goal

use my feathers client in my store to decode the tokens.

What I did so far

put my feathers client in a plugin, injected it in the app, requested services inside components, tested tokens in a middleware.

What I’m trying to do

keep my feathers client in the store.

Some piece of code:

plugins/feathers.js

import Vue from 'vue'
import feathers from 'feathers/client'
import rest from 'feathers-rest/client'
import axios from 'axios'
import hooks from 'feathers-hooks'
import auth from 'feathers-authentication-client'
import { urls } from '~/config'

const client = feathers();

client.configure(hooks())
.configure(rest(`${urls.API_URL}:${urls.API_PORT}`).axios(axios))
.configure(auth())

client.service('users')

const feathersPlugin = {
  install (Vue, options) {
    Vue.mixin({
      created: function () {
        // access to the client anywhere
        this.$feathers = client

        // Setting up the services
        this.$services = client.services
      }
    })
  }
}

Vue.use(feathersPlugin)

export default ({ app }) => {
  // Set feathers instance on app
  app.feathers = client
}

middleware/check-credentials.js

import { getTokenFromCookie, getTokenFromLocalStorage } from '~/utils/auth'
import { HANDLE_TOKEN } from '~/store/config.actions.json'

export default function ({ isServer, store, req, app }) {
  // If nuxt generate, skip this middleware
  if (isServer) return
  const storedToken = isServer ? getTokenFromCookie(req) : getTokenFromLocalStorage()
  if (storedToken === null || storedToken === undefined) return
  return app.feathers.passport.verifyJWT(storedToken).then(
    result => {
      store.dispatch(`user/${HANDLE_TOKEN}`, {
        accessToken: storedToken,
        displayName: result.displayName
      })
    },
    error => {
      console.error(error)
    }
  )
}

Thanks.

This question is available on Nuxt.js community (#c911)