34 lines
876 B
TypeScript
34 lines
876 B
TypeScript
|
|
import createClient, { type Middleware } from 'openapi-fetch';
|
||
|
|
import type { paths } from './schema';
|
||
|
|
import { config } from '../config';
|
||
|
|
|
||
|
|
let getAccessToken: () => string | null = () => null;
|
||
|
|
let onUnauthorized: () => void = () => {};
|
||
|
|
|
||
|
|
export function configureAuth(opts: {
|
||
|
|
getAccessToken: () => string | null;
|
||
|
|
onUnauthorized: () => void;
|
||
|
|
}) {
|
||
|
|
getAccessToken = opts.getAccessToken;
|
||
|
|
onUnauthorized = opts.onUnauthorized;
|
||
|
|
}
|
||
|
|
|
||
|
|
const authMiddleware: Middleware = {
|
||
|
|
async onRequest({ request }) {
|
||
|
|
const token = getAccessToken();
|
||
|
|
if (token) {
|
||
|
|
request.headers.set('Authorization', `Bearer ${token}`);
|
||
|
|
}
|
||
|
|
return request;
|
||
|
|
},
|
||
|
|
async onResponse({ response }) {
|
||
|
|
if (response.status === 401) {
|
||
|
|
onUnauthorized();
|
||
|
|
}
|
||
|
|
return response;
|
||
|
|
},
|
||
|
|
};
|
||
|
|
|
||
|
|
export const api = createClient<paths>({ baseUrl: config.apiBaseUrl });
|
||
|
|
api.use(authMiddleware);
|