Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 82 additions & 0 deletions src/data/api.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
// ========================================
// OpenScholar — API Client
// Central fetch() wrapper with demo credential auto-login
// ========================================

const API_BASE = 'http://localhost:8000';

const DEMO_CREDENTIALS = {
admin: { email: 'admin@demo.openscholar.org', password: 'demo123' },
ngo: { email: 'ngo@demo.openscholar.org', password: 'demo123' },
donor: { email: 'donor@demo.openscholar.org', password: 'demo123' },
school: { email: 'school@demo.openscholar.org', password: 'demo123' },
student: { email: 'student@demo.openscholar.org', password: 'demo123' },
};

// In-memory token cache — resets on page refresh (fine for demo)
const tokenCache = {};
let _currentRole = 'public';

async function getToken(role) {
if (!DEMO_CREDENTIALS[role]) return null; // public: no token
if (tokenCache[role]) return tokenCache[role]; // cached: reuse
// Auto-login with demo credentials
try {
const res = await fetch(`${API_BASE}/api/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(DEMO_CREDENTIALS[role]),
});
if (!res.ok) {
console.error(`Login failed for role ${role}:`, res.status);
return null;
}
const data = await res.json();
tokenCache[role] = data.accessToken; // camelCase from backend
return tokenCache[role];
} catch (err) {
console.error(`Network error during login for role ${role}:`, err);
return null;
}
}

export const api = {
setRole(role) {
_currentRole = role;
},

async get(path, role) {
const r = role ?? _currentRole;
const token = await getToken(r);
const headers = token ? { Authorization: `Bearer ${token}` } : {};
try {
const res = await fetch(`${API_BASE}${path}`, { headers });
if (!res.ok) {
console.error(`GET ${path} failed:`, res.status);
return [];
}
return res.json();
} catch (err) {
console.error(`Network error GET ${path}:`, err);
return [];
}
},

async post(path, body, role) {
const r = role ?? _currentRole;
const token = await getToken(r);
const headers = { 'Content-Type': 'application/json' };
if (token) headers.Authorization = `Bearer ${token}`;
try {
const res = await fetch(`${API_BASE}${path}`, {
method: 'POST',
headers,
body: JSON.stringify(body),
});
return res.json();
} catch (err) {
console.error(`Network error POST ${path}:`, err);
return {};
}
},
};
Loading