Answer the question
In order to leave comments, you need to log in
Is it possible to call action in action?
i have auth module it has action request can action request be called in it?
or to take out its async request to the service?
and how to make a service with request?
import { Module, Mutation,Action, VuexModule } from 'vuex-module-decorators';
@Module({ name: 'AuthStoreModule', namespaced: true })
export default class AuthStoreModule extends VuexModule {
@Mutation
clearToken(state) {
state.token = '';
this.$cookies.remove('access_token');
this.$cookies.remove('refresh_token');
},
@Action
async sendCode({ phone }) {
const data = {
method: 'GET',
url: '/code',
params: { phone },
};
const res = await this.dispatch('request', data);
if (res.success) return true;
return res.message;
}
@Action
async request(cnx, { method = 'GET', url = '', headers, body, params }) {
const req = {
method,
url,
data: body,
params,
headers
};
async function callback() {
try {
const res = await this.$axios(req);
const { data } = res;
return {
success: data.success || true,
data: data.data,
meta: data.meta || null,
message: data.message,
status: res.status
};
} catch (e) {
const data = e.response?.data;
return {
success: false,
message:
data?.error?.message || e.message || 'Ошибка получения данных',
status: data.error?.status
};
}
}
const res = await callback.call(this);
if (!res.success) {
// если был не удачный запрос с токеном делаем refresh
if (headers?.Authorization) {
const { status } = res;
if (!status || status == 401) {
// добавить проверку на рефреш при 401 ошибке
const token = await this.dispatch('auth/refreshToken');
if (token) {
req.headers.Authorization = `Bearer ${token}`;
return await callback.call(this);
} else {
localStorage.clear();
this.dispatch('auth/clearToken');
}
}
} else {
// иначе выводим ошибки в консоль
console.error(
`
url: ${url}
baseUrl: ${process.env.NUXT_ENV_API}
Response: ${JSON.stringify(res.data)}
Message: ${res.message}
Params: ${JSON.stringify(params)}
Payload: ${JSON.stringify(body)}
`
);
// console.error(res.message);
}
}
return res;
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question