Example Authentication with the Client API
import { TripedgeClientAPI } from "./tripedge.client.api";
// Define SecurityDataType to match the expected structure
interface SecurityDataType {
ApiKeyAuth: string;
}
interface RequestConfig {
url?: string;
method?: string;
headers?: Record<string, string>;
data?: unknown;
params?: Record<string, string>;
}
class CustomizedTripedgeClientAPI extends TripedgeClientAPI<SecurityDataType> {
private tokenExpiresAt: Date | null = null;
private lastRequest: { config: RequestConfig } | null = null;
private isRefreshingToken = false;
constructor(config: { baseURL: string; apiKey: string, expiresAt: Date }) {
super(config);
// Convert headers to SecurityDataType format
this.instance.defaults.headers.common['Authorization'] = process.env.NEXT_PUBLIC_API_KEY || '';
this.tokenExpiresAt = config.expiresAt;
// Intercept requests to store last request config and check token
this.instance.interceptors.request.use((config) => {
this.checkTokenExpiration();
this.lastRequest = { config };
return config;
});
// Intercept responses to handle unauthorized errors
this.instance.interceptors.response.use(
(response) => {
// Reset the refresh flag on successful response
this.isRefreshingToken = false;
return response;
},
async (error) => {
if (error.response?.data?.message === "Unauthorized" && !this.isRefreshingToken) {
return this.handleUnauthorized();
}
throw error;
}
);
}
private async handleUnauthorized(): Promise<unknown> {
this.isRefreshingToken = true;
const newToken = 'NEW TOKEN'; // PUT YOUR LOGIC HERE TO GET A NEW TOKEN
// Set security data in correct format
this.instance.defaults.headers.common['Authorization'] = newToken || '';
this.tokenExpiresAt = new Date(Date.now() + 3600 * 1000);
// Resend last failed request if available, but only once
if (this.lastRequest) {
const { config } = this.lastRequest;
// Clear last request to prevent retry loops
this.lastRequest = null;
// Update token in the stored request
config.headers = config.headers || {};
config.headers['Authorization'] = newToken;
// The response interceptor will handle resetting isRefreshingToken
return this.instance.request(config);
}
// Reset isRefreshingToken if we're not making another request
this.isRefreshingToken = false;
return null;
}
private checkTokenExpiration(): void {
if (this.tokenExpiresAt && new Date() > this.tokenExpiresAt && !this.isRefreshingToken) {
this.handleUnauthorized();
}
}
}
export const tripedgeApi = new CustomizedTripedgeClientAPI({
baseURL: process.env.NEXT_PUBLIC_API_URL || '',
apiKey: 'STARTING USER TOKEN',
expiresAt: new Date(Date.now() + 3600 * 1000) // 1 hour expiry
});