jwt provider and common api utils
This commit is contained in:
@@ -1,28 +1,27 @@
|
||||
import React, { createContext, useState, useContext, useEffect } from 'react';
|
||||
import axios from 'axios';
|
||||
import { ArticleModel } from "../types/models";
|
||||
import { ArticleContextModel } from "../types/contexts";
|
||||
import { api } from '../utils/api';
|
||||
import { ArticleModel } from '../types/models';
|
||||
import { ArticleContextModel } from '../types/contexts';
|
||||
import { useAuth } from './Author';
|
||||
|
||||
const ArticleContext = createContext<ArticleContextModel | undefined>(undefined);
|
||||
|
||||
const API_BASE = import.meta.env.VITE_API_BASE_URL;
|
||||
|
||||
export const ArticleProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
||||
const [articles, setArticles] = useState<ArticleModel[]>([]);
|
||||
const [loading, setLoading] = useState<boolean>(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const { token } = useAuth(); // ✅ access token if needed
|
||||
|
||||
/** 🔹 Fetch articles (JWT automatically attached by api.ts interceptor) */
|
||||
const fetchArticles = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
// ✅ Use correct full endpoint from OpenAPI spec
|
||||
const res = await axios.get<ArticleModel[]>(`${API_BASE}/articles`, {
|
||||
const res = await api.get<ArticleModel[]>('/articles', {
|
||||
params: { skip: 0, limit: 10 },
|
||||
});
|
||||
|
||||
// ✅ Normalize if backend sends _id instead of id
|
||||
const formatted = res.data.map((a) => ({
|
||||
...a,
|
||||
id: a._id || undefined,
|
||||
@@ -31,15 +30,16 @@ export const ArticleProvider: React.FC<{ children: React.ReactNode }> = ({ child
|
||||
setArticles(formatted);
|
||||
} catch (err: any) {
|
||||
console.error('Failed to fetch articles:', err);
|
||||
setError(err.message || 'Failed to fetch articles');
|
||||
setError(err.response?.data?.detail || 'Failed to fetch articles');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
/** 🔹 Auto-fetch articles whenever user logs in/out */
|
||||
useEffect(() => {
|
||||
fetchArticles();
|
||||
}, []);
|
||||
if (token) fetchArticles();
|
||||
}, [token]);
|
||||
|
||||
return (
|
||||
<ArticleContext.Provider value={{ articles, loading, error, refreshArticles: fetchArticles }}>
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
import React, { createContext, useState, useEffect, useContext } from 'react';
|
||||
import axios from 'axios';
|
||||
import { AuthorModel } from "../types/models";
|
||||
import { AuthContextModel } from "../types/contexts";
|
||||
import { api } from '../utils/api';
|
||||
import { AuthorModel } from '../types/models';
|
||||
import { AuthContextModel } from '../types/contexts';
|
||||
|
||||
const AuthContext = createContext<AuthContextModel | undefined>(undefined);
|
||||
|
||||
const API_BASE = import.meta.env.VITE_API_BASE_URL;
|
||||
|
||||
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
||||
const [currentUser, setCurrentUser] = useState<AuthorModel | null>(null);
|
||||
const [authors, setAuthors] = useState<AuthorModel[]>([]);
|
||||
@@ -20,7 +18,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
const res = await axios.post(`${API_BASE}/auth/login`, { email, password });
|
||||
const res = await api.post('/auth/login', { email, password });
|
||||
const { access_token, user } = res.data;
|
||||
|
||||
if (access_token) {
|
||||
@@ -44,17 +42,13 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
|
||||
setAuthors([]);
|
||||
};
|
||||
|
||||
/** 🔹 Fetch all authors (requires valid JWT) */
|
||||
/** 🔹 Fetch all authors (JWT handled by api interceptor) */
|
||||
const refreshAuthors = async () => {
|
||||
if (!token) return;
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
const res = await axios.get<AuthorModel[]>(`${API_BASE}/authors`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
|
||||
const res = await api.get<AuthorModel[]>('/authors');
|
||||
setAuthors(res.data);
|
||||
} catch (err: any) {
|
||||
console.error('Failed to fetch authors:', err);
|
||||
@@ -68,9 +62,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
|
||||
const fetchCurrentUser = async () => {
|
||||
if (!token) return;
|
||||
try {
|
||||
const res = await axios.get<AuthorModel>(`${API_BASE}/auth/me`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
const res = await api.get<AuthorModel>('/auth/me');
|
||||
setCurrentUser(res.data);
|
||||
} catch (err: any) {
|
||||
console.error('Failed to fetch current user:', err);
|
||||
@@ -78,6 +70,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
|
||||
}
|
||||
};
|
||||
|
||||
/** 🔹 On mount, try to fetch user if token exists */
|
||||
useEffect(() => {
|
||||
if (token) fetchCurrentUser();
|
||||
}, [token]);
|
||||
|
||||
33
src/blog/utils/api.ts
Normal file
33
src/blog/utils/api.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
// src/utils/api.ts
|
||||
import axios from 'axios';
|
||||
|
||||
const API_BASE = import.meta.env.VITE_API_BASE_URL;
|
||||
|
||||
export const api = axios.create({
|
||||
baseURL: API_BASE,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
// 🔹 Attach token from localStorage before each request
|
||||
api.interceptors.request.use((config) => {
|
||||
const token = localStorage.getItem('token');
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
return config;
|
||||
});
|
||||
|
||||
// 🔹 Handle expired or invalid tokens globally
|
||||
api.interceptors.response.use(
|
||||
(response) => response,
|
||||
(error) => {
|
||||
if (error.response?.status === 401) {
|
||||
console.warn('Token expired or invalid. Logging out...');
|
||||
localStorage.removeItem('token');
|
||||
// Optionally: trigger a redirect or event
|
||||
}
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
@@ -2,14 +2,17 @@ import * as React from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import Blog from './blog/Blog';
|
||||
import { ArticleProvider } from './blog/providers/Article';
|
||||
import { AuthProvider } from './blog/providers/Author';
|
||||
|
||||
const rootElement = document.getElementById('root');
|
||||
const root = createRoot(rootElement);
|
||||
|
||||
root.render(
|
||||
<React.StrictMode>
|
||||
<ArticleProvider>
|
||||
<Blog />
|
||||
</ArticleProvider>
|
||||
<AuthProvider>
|
||||
<ArticleProvider>
|
||||
<Blog />
|
||||
</ArticleProvider>
|
||||
</AuthProvider>
|
||||
</React.StrictMode>,
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user