存档
This commit is contained in:
@@ -0,0 +1,30 @@
|
||||
import axios, { type AxiosInstance } from 'axios';
|
||||
import { createContext, useContext } from 'react';
|
||||
|
||||
export interface PluginContextValue {
|
||||
client: AxiosInstance;
|
||||
token: string;
|
||||
apiBase: string;
|
||||
}
|
||||
|
||||
export const PluginContext = createContext<PluginContextValue | null>(null);
|
||||
|
||||
export function usePluginContext(): PluginContextValue {
|
||||
const ctx = useContext(PluginContext);
|
||||
if (!ctx) throw new Error('PluginContext missing — Web Component not initialized');
|
||||
return ctx;
|
||||
}
|
||||
|
||||
export function makeClient(token: string, apiBase: string): AxiosInstance {
|
||||
const c = axios.create({
|
||||
baseURL: apiBase || undefined,
|
||||
});
|
||||
c.interceptors.request.use((cfg) => {
|
||||
if (token) {
|
||||
cfg.headers = cfg.headers || {};
|
||||
(cfg.headers as Record<string, string>).Authorization = `Bearer ${token}`;
|
||||
}
|
||||
return cfg;
|
||||
});
|
||||
return c;
|
||||
}
|
||||
Reference in New Issue
Block a user