Configure `requestInterceptor` and `responseInterceptor`
mrleblanc101 opened this issue · 1 comments
mrleblanc101 commented
Hi,
How could I define requestInterceptor
and responseInterceptor
for the plugin ?
I currently use a custom plugin for Swagger and I did like so but it fetch the schema at runtime instead of build time which increase page load time.
import SwaggerClient from 'swagger-client';
export default async ({ app, $config, $auth }, inject) => {
const swagger = await SwaggerClient({
url: $config.apiURL,
async requestInterceptor(request) {
let jwt = $auth.strategy.token.get();
if (jwt) {
if ($auth.strategy.token.status().expired()) {
if ($auth.strategy.refreshToken.status().valid()) {
// Forcer le reload des tokens
await $auth.refreshTokens();
jwt = $auth.strategy.token.get();
} else {
$auth.logout();
return;
}
}
request.headers.Authorization = jwt;
}
request.headers['Accept-Language'] = app.i18n.locale;
request.headers.Accept = 'application/json';
return request;
},
responseInterceptor(response) {
if (response.status === 401) {
$auth.logout();
}
return response;
},
});
inject('swagger', swagger);
};
Elevista commented
You can use nuxt axios way https://axios.nuxtjs.org/extend#adding-interceptors
If you're using multiple plugins
can do like this
~/plguins/axios.ts
import { Plugin } from '@nuxt/types'
export default (({ $axios, $foo }) => {
$axios.onRequest(() => {
// ...
})
$foo.$axios.onRequest(() => {
// ...
})
}) as Plugin