In my code, I have an abstract class called BaseRepository
which includes a client instance and some general functions. The AuthRepository
class inherits from the BaseRepository
. Additionally, there is an AuthService
module that utilizes the AuthRepository
for login functionality and checking login status. When a route is opened, a request is sent to the API. The AuthService
is used to obtain a token for authorization in the client request interceptor. If the token is successfully acquired, it is added to the headers and the request continues. Otherwise, the user is redirected to the login page to log in again. While this setup works without issue after the initial login, a "ReferenceError: can't access lexical declaration 'BaseRepository' before initialization" occurs when the page is refreshed.
BaseRepository
import { BackendClient } from "@/repositories/clients";
import type { AxiosError, AxiosInstance, AxiosResponse } from "axios";
// other imports
export default abstract class BaseRepository {
protected readonly client: AxiosInstance = BackendClient;
// general functions
}
AuthRepository
import { BaseRepository } from "@/repositories/base";
class AuthRepository extends BaseRepository {
constructor() {
super()
}
// other functions
}
const authRepository = new AuthRepository();
export default authRepository;
Axios client
import axios, { type AxiosInstance } from "axios";
import { AuthService } from "@/modules/auth";
import router from "@/router";
import appConfig from "@/config";
const client: AxiosInstance = axios.create({
baseURL: appConfig.backendClient.baseUrl,
headers: {
"Access-Control-Allow-Origin": "*",
},
validateStatus: (status: number): boolean => {
var isValid = (status < 400 || status == 401);
console.log("requestvalidatestatus", isValid);
return isValid;
}
})
const TOKEN_EXCLUDE_ENDPOINTS = [
'Auth/Login',
'Auth/Register',
'Auth/RefreshAccessToken'
]
client.interceptors.request.use(async (config) => {
var requestUrl = config.url;
for(var excludeEndpoint of TOKEN_EXCLUDE_ENDPOINTS) {
if(requestUrl?.startsWith(excludeEndpoint)){
return config;
}
}
var token = await AuthService.getAccessToken();
if(!token) {
router.push('/login');
}
console.log("token",token);
config.headers.Authorization = `Bearer ${token}`;
return config;
})
export default client;
AuthService
import { AuthRepository } from "@/repositories";
class AuthService {
async login(request: LoginRequest, rememberMe: boolean, forceLogin: boolean = false) {
// other logic
return await AuthRepository.login(request);
}
// other functions
}
const authService = new AuthService();
export default authService;
What could be causing this issue?