Use dependency from boot file in other boot file in Quasar (vuejs)

Viewed 1261

I am trying to use an instance of an object in a boot file where the instance is created in another boot file. The documentation [0] talks about using an object instance from a boot file and it works fine when using the instance in a component. I would like to access the instance in another boot file.

First boot file that creates the instance looks like this:

import { AuthService } from '../authorization/AuthService';

let oidc = null
export default ({ router, store, Vue }) => {
  const OIDC = new AuthService();
  router.beforeEach((to, from, next) => {
    const allowAnonymous = to.matched.some(record => record.meta.allowAnonymous)
    if (allowAnonymous) {
      next()
    } else {
      var isAuthenticated = OIDC.isAuthenticated()
      if (isAuthenticated) {
        next()
      } else {
        OIDC.signIn()
      }
    }
  })

  Vue.prototype.$oidc = OIDC
  oidc = OIDC
}

export { oidc }

And I am trying to use the oidc instance in another boot file like this:

import oidc from "boot/oidc-service"
import axios from 'axios'

let axiosInstance = null;
export default ({ app, router, store, Vue }) => {
    const AxiosInstance = axios.create({
      baseURL: window.env.BASE_URL
    })
  
    AxiosInstance.interceptors.request.use(function (config) {
      return oidc.getAccessToken().then(token => {
        config.headers.Authorization = `Bearer ${token}`

        return config
      })
    }, (error) => {
      return Promise.reject(error)
    })
    
    Vue.prototype.$axios = AxiosInstance
    axiosInstance = AxiosInstance
}

export { axiosInstance }

I import them in the following order:

    boot: [
      'oidc-service',
      'axios',
...

If I export the class instead of the instance, I can instantiate it and code works as expected. I would like for the oidc object to be a singleton however.

How can I use the instance of oidc in my axios setup?

[0] https://quasar.dev/quasar-cli/boot-files#Accessing-data-from-boot-files

1 Answers

Unless I'm missing something... if oidc is not null, return it, otherwise continue with the initialization:

import { AuthService } from '../authorization/AuthService';

let oidc = null
export default ({ router, store, Vue }) => {
    if(oidc !== null) return oidc;
    // else continue...
Related