logaretm / villus

🏎 A tiny and fast GraphQL client for Vue.js

Home Page:https://villus.dev

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Best practice for setting headers at runtime

FreekVR opened this issue · comments

Hey there, I was wondering what is the best way to have a reactive value for a header with villus.

We have a multilingual vue3 app (using vue-i18n) and the API we consume needs an Accept-Language header to consume multilingual GraphQL data.

The i18n language is changed/set at various points during runtime (from both a language switcher and from route params), but always using a setLanguage function in my app.

I've tried the following, it works for setting the header but is not reactive to language changes after this point in my app.

What I'm basically looking for is either: (a) a way to access my app instance in the plugin, so I can access the vue-18n language each time a query runs, or (b) an API to manually set the header whenever the language changes.

Unfortunately I couldn't find anything in the docs for this scenario, so any pointers how to achieve this would be appreciated :)

For reference, this is my current setup;

main.js:

/**
 * Internationalization (i18n)
 */
const i18n = setupI18n({
    locale: 'en', // Default, changes based on route.
    fallbackLocale: 'en',
    messages: {
        en,
        nl
    },
    legacy: false
}, router);

const  i18nPlugin({ locale }) {
    console.log(locale);
    return ({ opContext }) => {
        opContext.headers['Accept-Language']= locale.value;
    };
}


/**
 * GraphQL
 */
console.log(i18n);
const client = createClient({
    url: import.meta.env.VITE_GRAPHQL_ENDPOINT,
    use: [i18nPlugin({ locale: i18n.global.locale }), ...defaultPlugins()]
});

createApp([...]

Sorry for the delay, I didn't have much time in October to check issues.

By "reactivity" do you mean re-running all queries to update their information whenever the language changes? or do you just intend that for the new queries being executed?

If the latter then you can do that by evaluating the locale every time in the plugin instead of passing it statically. One way to do this is to reference a reactive ref that holds the i18n language.

// i18n file or whatever
export const i18n = createI18n(...);

// villus plugins
import { i18n } from './i18n';

const  i18nPlugin = ({ opContext }) => {
  // not sure if this is the correct way to get the locale, consult the i18n docs
  opContext.headers['Accept-Language']= i18n.global.locale;
}

Let me know if this doesn't work for you and sorry again about the delay.