Phase 6 complete

This commit is contained in:
Joey Yakimowich-Payne 2026-01-13 16:52:57 -07:00
commit 3a22b42492
No known key found for this signature in database
GPG key ID: 6BFE655FA5ABD1E1
11 changed files with 735 additions and 103 deletions

View file

@ -267,32 +267,32 @@ Add user accounts via Authentik (OIDC) and persist quizzes to SQLite database. U
## Phase 6: Polish & Error Handling
### 6.1 Loading States
- [ ] Add loading indicators:
- [ ] Quiz library list loading
- [ ] Quiz loading when selected
- [ ] Save operation in progress
- [ ] Disable buttons during async operations
- [x] Add loading indicators:
- [x] Quiz library list loading
- [x] Quiz loading when selected
- [x] Save operation in progress
- [x] Disable buttons during async operations
### 6.2 Error Handling
- [ ] Display user-friendly error messages:
- [ ] Failed to load quiz library
- [ ] Failed to save quiz
- [ ] Failed to delete quiz
- [ ] Network/auth errors
- [ ] Add retry mechanisms where appropriate
- [x] Display user-friendly error messages:
- [x] Failed to load quiz library
- [x] Failed to save quiz
- [x] Failed to delete quiz
- [x] Network/auth errors
- [x] Add retry mechanisms where appropriate
### 6.3 Toast Notifications (Optional)
- [ ] Add `react-hot-toast` or similar
- [ ] Show success toasts:
- [ ] "Quiz saved successfully"
- [ ] "Quiz deleted"
- [ ] Show error toasts for failures
- [x] Add `react-hot-toast` or similar
- [x] Show success toasts:
- [x] "Quiz saved successfully"
- [x] "Quiz deleted"
- [x] Show error toasts for failures
### 6.4 Edge Cases
- [ ] Handle auth token expiry gracefully
- [ ] Handle offline state
- [ ] Handle concurrent save attempts
- [ ] Validate quiz data before save
- [x] Handle auth token expiry gracefully
- [x] Handle offline state
- [x] Handle concurrent save attempts
- [x] Validate quiz data before save
---
@ -408,5 +408,5 @@ kaboot/
| Phase 3 | **COMPLETE** | OIDC config, AuthProvider, AuthButton, useAuthenticatedFetch |
| Phase 4 | **COMPLETE** | useQuizLibrary hook, QuizLibrary modal, Landing integration |
| Phase 5 | **COMPLETE** | SaveQuizPrompt modal, QuizCreator save checkbox, save integration |
| Phase 6 | Not Started | |
| Phase 6 | **COMPLETE** | Toast notifications, loading states, error handling, edge cases |
| Phase 7 | Not Started | |

View file

@ -24,7 +24,17 @@ export const Landing: React.FC<LandingProps> = ({ onGenerate, onCreateManual, on
const [name, setName] = useState('');
const [libraryOpen, setLibraryOpen] = useState(false);
const { quizzes, loading: libraryLoading, error: libraryError, fetchQuizzes, loadQuiz, deleteQuiz } = useQuizLibrary();
const {
quizzes,
loading: libraryLoading,
loadingQuizId,
deletingQuizId,
error: libraryError,
fetchQuizzes,
loadQuiz,
deleteQuiz,
retry: retryLibrary
} = useQuizLibrary();
useEffect(() => {
if (libraryOpen && auth.isAuthenticated) {
@ -169,9 +179,12 @@ export const Landing: React.FC<LandingProps> = ({ onGenerate, onCreateManual, on
onClose={() => setLibraryOpen(false)}
quizzes={quizzes}
loading={libraryLoading}
loadingQuizId={loadingQuizId}
deletingQuizId={deletingQuizId}
error={libraryError}
onLoadQuiz={handleLoadQuiz}
onDeleteQuiz={deleteQuiz}
onRetry={retryLibrary}
/>
</div>
);

View file

@ -8,9 +8,12 @@ interface QuizLibraryProps {
onClose: () => void;
quizzes: QuizListItem[];
loading: boolean;
loadingQuizId: string | null;
deletingQuizId: string | null;
error: string | null;
onLoadQuiz: (id: string) => void;
onDeleteQuiz: (id: string) => void;
onRetry: () => void;
}
export const QuizLibrary: React.FC<QuizLibraryProps> = ({
@ -18,28 +21,36 @@ export const QuizLibrary: React.FC<QuizLibraryProps> = ({
onClose,
quizzes,
loading,
loadingQuizId,
deletingQuizId,
error,
onLoadQuiz,
onDeleteQuiz,
onRetry,
}) => {
const [deletingId, setDeletingId] = useState<string | null>(null);
const [confirmDeleteId, setConfirmDeleteId] = useState<string | null>(null);
const isAnyOperationInProgress = loading || !!loadingQuizId || !!deletingQuizId;
const handleDeleteClick = (e: React.MouseEvent, id: string) => {
e.stopPropagation();
setDeletingId(id);
setConfirmDeleteId(id);
};
const confirmDelete = (e: React.MouseEvent) => {
const confirmDelete = async (e: React.MouseEvent) => {
e.stopPropagation();
if (deletingId) {
onDeleteQuiz(deletingId);
setDeletingId(null);
if (confirmDeleteId) {
try {
await onDeleteQuiz(confirmDeleteId);
setConfirmDeleteId(null);
} catch {
setConfirmDeleteId(null);
}
}
};
const cancelDelete = (e: React.MouseEvent) => {
e.stopPropagation();
setDeletingId(null);
setConfirmDeleteId(null);
};
const formatDate = (dateString: string) => {
@ -95,8 +106,14 @@ export const QuizLibrary: React.FC<QuizLibraryProps> = ({
)}
{!loading && error && (
<div className="bg-red-50 border-2 border-red-100 p-4 rounded-2xl text-red-500 font-bold text-center">
{error}
<div className="bg-red-50 border-2 border-red-100 p-4 rounded-2xl text-center">
<p className="text-red-500 font-bold mb-3">{error}</p>
<button
onClick={onRetry}
className="bg-red-500 text-white px-4 py-2 rounded-xl text-sm font-bold hover:bg-red-600 transition-colors"
>
Try Again
</button>
</div>
)}
@ -116,8 +133,8 @@ export const QuizLibrary: React.FC<QuizLibraryProps> = ({
layout
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
className="group bg-white p-4 rounded-2xl border-2 border-gray-100 hover:border-theme-primary hover:shadow-md transition-all cursor-pointer relative overflow-hidden"
onClick={() => onLoadQuiz(quiz.id)}
className={`group bg-white p-4 rounded-2xl border-2 border-gray-100 hover:border-theme-primary hover:shadow-md transition-all relative overflow-hidden ${isAnyOperationInProgress ? 'cursor-not-allowed opacity-70' : 'cursor-pointer'}`}
onClick={() => !isAnyOperationInProgress && onLoadQuiz(quiz.id)}
>
<div className="flex justify-between items-start">
<div className="flex-1">
@ -147,17 +164,27 @@ export const QuizLibrary: React.FC<QuizLibraryProps> = ({
</div>
<div className="flex items-center gap-3 pl-4">
{deletingId === quiz.id ? (
{loadingQuizId === quiz.id ? (
<div className="p-3">
<Loader2 size={24} className="animate-spin text-theme-primary" />
</div>
) : deletingQuizId === quiz.id ? (
<div className="p-3">
<Loader2 size={24} className="animate-spin text-red-500" />
</div>
) : confirmDeleteId === quiz.id ? (
<div className="flex items-center gap-2" onClick={(e) => e.stopPropagation()}>
<button
onClick={confirmDelete}
className="bg-red-500 text-white px-3 py-2 rounded-xl text-sm font-bold shadow-[0_3px_0_#991b1b] active:shadow-none active:translate-y-[3px] transition-all"
disabled={isAnyOperationInProgress}
className="bg-red-500 text-white px-3 py-2 rounded-xl text-sm font-bold shadow-[0_3px_0_#991b1b] active:shadow-none active:translate-y-[3px] transition-all disabled:opacity-50"
>
Confirm
</button>
<button
onClick={cancelDelete}
className="bg-gray-200 text-gray-600 px-3 py-2 rounded-xl text-sm font-bold hover:bg-gray-300 transition-all"
disabled={isAnyOperationInProgress}
className="bg-gray-200 text-gray-600 px-3 py-2 rounded-xl text-sm font-bold hover:bg-gray-300 transition-all disabled:opacity-50"
>
Cancel
</button>
@ -166,7 +193,8 @@ export const QuizLibrary: React.FC<QuizLibraryProps> = ({
<>
<button
onClick={(e) => handleDeleteClick(e, quiz.id)}
className="p-3 rounded-xl text-gray-300 hover:bg-red-50 hover:text-red-500 transition-colors"
disabled={isAnyOperationInProgress}
className="p-3 rounded-xl text-gray-300 hover:bg-red-50 hover:text-red-500 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
title="Delete quiz"
>
<Trash2 size={20} />

View file

@ -36,10 +36,16 @@ export const useAuthenticatedFetch = () => {
const authFetch = useCallback(
async (path: string, options: RequestInit = {}): Promise<Response> => {
if (!navigator.onLine) {
throw new Error('You appear to be offline. Please check your connection.');
}
const token = await ensureValidToken();
const url = path.startsWith('http') ? path : `${API_URL}${path}`;
const response = await fetch(url, {
let response: Response;
try {
response = await fetch(url, {
...options,
headers: {
...options.headers,
@ -47,6 +53,12 @@ export const useAuthenticatedFetch = () => {
'Content-Type': 'application/json',
},
});
} catch (err) {
if (!navigator.onLine) {
throw new Error('You appear to be offline. Please check your connection.');
}
throw new Error('Network error. Please try again.');
}
if (response.status === 401) {
try {
@ -67,6 +79,10 @@ export const useAuthenticatedFetch = () => {
throw new Error('Session expired, redirecting to login');
}
if (response.status >= 500) {
throw new Error('Server error. Please try again later.');
}
return response;
},
[auth, ensureValidToken]

View file

@ -1,49 +1,84 @@
import { useState, useCallback } from 'react';
import { useState, useCallback, useRef } from 'react';
import toast from 'react-hot-toast';
import { useAuthenticatedFetch } from './useAuthenticatedFetch';
import type { Quiz, QuizSource, SavedQuiz, QuizListItem } from '../types';
interface UseQuizLibraryReturn {
quizzes: QuizListItem[];
loading: boolean;
loadingQuizId: string | null;
deletingQuizId: string | null;
saving: boolean;
error: string | null;
fetchQuizzes: () => Promise<void>;
loadQuiz: (id: string) => Promise<SavedQuiz>;
saveQuiz: (quiz: Quiz, source: QuizSource, aiTopic?: string) => Promise<string>;
deleteQuiz: (id: string) => Promise<void>;
retry: () => Promise<void>;
clearError: () => void;
}
export const useQuizLibrary = (): UseQuizLibraryReturn => {
const { authFetch, isAuthenticated } = useAuthenticatedFetch();
const [quizzes, setQuizzes] = useState<QuizListItem[]>([]);
const [loading, setLoading] = useState(false);
const [loadingQuizId, setLoadingQuizId] = useState<string | null>(null);
const [deletingQuizId, setDeletingQuizId] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const lastOperationRef = useRef<(() => Promise<void>) | null>(null);
const fetchQuizzes = useCallback(async () => {
if (!isAuthenticated) return;
setLoading(true);
setError(null);
lastOperationRef.current = fetchQuizzes;
try {
const response = await authFetch('/api/quizzes');
if (!response.ok) {
throw new Error('Failed to fetch quizzes');
const errorText = response.status === 500
? 'Server error. Please try again.'
: 'Failed to load your quizzes.';
throw new Error(errorText);
}
const data = await response.json();
setQuizzes(data);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to fetch quizzes');
const message = err instanceof Error ? err.message : 'Failed to load quizzes';
setError(message);
if (!message.includes('redirecting')) {
toast.error(message);
}
} finally {
setLoading(false);
}
}, [authFetch, isAuthenticated]);
const loadQuiz = useCallback(async (id: string): Promise<SavedQuiz> => {
setLoadingQuizId(id);
setError(null);
try {
const response = await authFetch(`/api/quizzes/${id}`);
if (!response.ok) {
throw new Error('Failed to load quiz');
const errorText = response.status === 404
? 'Quiz not found. It may have been deleted.'
: 'Failed to load quiz.';
throw new Error(errorText);
}
toast.success('Quiz loaded!');
return response.json();
} catch (err) {
const message = err instanceof Error ? err.message : 'Failed to load quiz';
if (!message.includes('redirecting')) {
toast.error(message);
}
throw err;
} finally {
setLoadingQuizId(null);
}
}, [authFetch]);
const saveQuiz = useCallback(async (
@ -51,6 +86,39 @@ export const useQuizLibrary = (): UseQuizLibraryReturn => {
source: QuizSource,
aiTopic?: string
): Promise<string> => {
if (saving) {
toast.error('Save already in progress');
throw new Error('Save already in progress');
}
if (!quiz.title?.trim()) {
toast.error('Quiz must have a title');
throw new Error('Quiz must have a title');
}
if (!quiz.questions || quiz.questions.length === 0) {
toast.error('Quiz must have at least one question');
throw new Error('Quiz must have at least one question');
}
for (const q of quiz.questions) {
if (!q.text?.trim()) {
toast.error('All questions must have text');
throw new Error('All questions must have text');
}
if (!q.options || q.options.length < 2) {
toast.error('Each question must have at least 2 options');
throw new Error('Each question must have at least 2 options');
}
const hasCorrect = q.options.some(o => o.isCorrect);
if (!hasCorrect) {
toast.error('Each question must have a correct answer');
throw new Error('Each question must have a correct answer');
}
}
setSaving(true);
setError(null);
try {
const response = await authFetch('/api/quizzes', {
method: 'POST',
body: JSON.stringify({
@ -72,32 +140,77 @@ export const useQuizLibrary = (): UseQuizLibraryReturn => {
});
if (!response.ok) {
throw new Error('Failed to save quiz');
const errorText = response.status === 400
? 'Invalid quiz data. Please check and try again.'
: 'Failed to save quiz.';
throw new Error(errorText);
}
const data = await response.json();
toast.success('Quiz saved to your library!');
return data.id;
} catch (err) {
const message = err instanceof Error ? err.message : 'Failed to save quiz';
if (!message.includes('redirecting')) {
toast.error(message);
}
throw err;
} finally {
setSaving(false);
}
}, [authFetch]);
const deleteQuiz = useCallback(async (id: string): Promise<void> => {
setDeletingQuizId(id);
setError(null);
try {
const response = await authFetch(`/api/quizzes/${id}`, {
method: 'DELETE',
});
if (!response.ok && response.status !== 204) {
throw new Error('Failed to delete quiz');
const errorText = response.status === 404
? 'Quiz not found.'
: 'Failed to delete quiz.';
throw new Error(errorText);
}
setQuizzes(prev => prev.filter(q => q.id !== id));
toast.success('Quiz deleted');
} catch (err) {
const message = err instanceof Error ? err.message : 'Failed to delete quiz';
if (!message.includes('redirecting')) {
toast.error(message);
}
throw err;
} finally {
setDeletingQuizId(null);
}
}, [authFetch]);
const retry = useCallback(async () => {
if (lastOperationRef.current) {
await lastOperationRef.current();
}
}, []);
const clearError = useCallback(() => {
setError(null);
}, []);
return {
quizzes,
loading,
loadingQuizId,
deletingQuizId,
saving,
error,
fetchQuizzes,
loadQuiz,
saveQuiz,
deleteQuiz,
retry,
clearError,
};
};

View file

@ -1,6 +1,7 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import { AuthProvider } from 'react-oidc-context';
import { Toaster } from 'react-hot-toast';
import App from './App';
import { oidcConfig } from './src/config/oidc';
@ -23,6 +24,31 @@ root.render(
window.localStorage.clear();
}}
>
<Toaster
position="top-center"
toastOptions={{
duration: 4000,
style: {
background: '#333',
color: '#fff',
fontWeight: 'bold',
borderRadius: '1rem',
padding: '12px 20px',
},
success: {
iconTheme: {
primary: '#22c55e',
secondary: '#fff',
},
},
error: {
iconTheme: {
primary: '#ef4444',
secondary: '#fff',
},
},
}}
/>
<App />
</AuthProvider>
</React.StrictMode>

34
package-lock.json generated
View file

@ -16,6 +16,7 @@
"peerjs": "^1.5.2",
"react": "^19.2.3",
"react-dom": "^19.2.3",
"react-hot-toast": "^2.6.0",
"react-oidc-context": "^3.2.0",
"recharts": "^3.6.0",
"uuid": "^13.0.0"
@ -1624,6 +1625,13 @@
"node": ">= 8"
}
},
"node_modules/csstype": {
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
"license": "MIT",
"peer": true
},
"node_modules/d3-array": {
"version": "3.2.4",
"resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz",
@ -2049,6 +2057,15 @@
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/goober": {
"version": "2.1.18",
"resolved": "https://registry.npmjs.org/goober/-/goober-2.1.18.tgz",
"integrity": "sha512-2vFqsaDVIT9Gz7N6kAL++pLpp41l3PfDuusHcjnGLfR6+huZkl6ziX+zgVC3ZxpqWhzH6pyDdGrCeDhMIvwaxw==",
"license": "MIT",
"peerDependencies": {
"csstype": "^3.0.10"
}
},
"node_modules/google-auth-library": {
"version": "10.5.0",
"resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-10.5.0.tgz",
@ -2506,6 +2523,23 @@
"react": "^19.2.3"
}
},
"node_modules/react-hot-toast": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/react-hot-toast/-/react-hot-toast-2.6.0.tgz",
"integrity": "sha512-bH+2EBMZ4sdyou/DPrfgIouFpcRLCJ+HoCA32UoAYHn6T3Ur5yfcDCeSr5mwldl6pFOsiocmrXMuoCJ1vV8bWg==",
"license": "MIT",
"dependencies": {
"csstype": "^3.1.3",
"goober": "^2.1.16"
},
"engines": {
"node": ">=10"
},
"peerDependencies": {
"react": ">=16",
"react-dom": ">=16"
}
},
"node_modules/react-is": {
"version": "19.2.3",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-19.2.3.tgz",

View file

@ -9,17 +9,18 @@
"preview": "vite preview"
},
"dependencies": {
"react": "^19.2.3",
"@google/genai": "^1.35.0",
"lucide-react": "^0.562.0",
"react-dom": "^19.2.3",
"uuid": "^13.0.0",
"recharts": "^3.6.0",
"framer-motion": "^12.26.1",
"canvas-confetti": "^1.9.4",
"peerjs": "^1.5.2",
"framer-motion": "^12.26.1",
"lucide-react": "^0.562.0",
"oidc-client-ts": "^3.1.0",
"react-oidc-context": "^3.2.0"
"peerjs": "^1.5.2",
"react": "^19.2.3",
"react-dom": "^19.2.3",
"react-hot-toast": "^2.6.0",
"react-oidc-context": "^3.2.0",
"recharts": "^3.6.0",
"uuid": "^13.0.0"
},
"devDependencies": {
"@types/node": "^22.14.0",

View file

@ -11,7 +11,20 @@ app.use(cors({
origin: process.env.CORS_ORIGIN || 'http://localhost:5173',
credentials: true,
}));
app.use(express.json({ limit: '10mb' }));
app.use((req: Request, res: Response, next: NextFunction) => {
express.json({ limit: '10mb' })(req, res, (err) => {
if (err instanceof SyntaxError && 'body' in err) {
res.status(400).json({ error: 'Invalid JSON' });
return;
}
if (err) {
next(err);
return;
}
next();
});
});
app.get('/health', (_req: Request, res: Response) => {
res.json({ status: 'ok', timestamp: new Date().toISOString() });

View file

@ -84,12 +84,45 @@ router.get('/:id', (req: AuthenticatedRequest, res: Response) => {
});
});
function validateQuizBody(body: QuizBody): string | null {
const { title, source, questions } = body;
if (!title?.trim()) {
return 'Title is required and cannot be empty';
}
if (!source || !['manual', 'ai_generated'].includes(source)) {
return 'Source must be "manual" or "ai_generated"';
}
if (!questions || !Array.isArray(questions) || questions.length === 0) {
return 'At least one question is required';
}
for (let i = 0; i < questions.length; i++) {
const q = questions[i];
if (!q.text?.trim()) {
return `Question ${i + 1} text is required`;
}
if (!q.options || !Array.isArray(q.options) || q.options.length < 2) {
return `Question ${i + 1} must have at least 2 options`;
}
const hasCorrect = q.options.some(o => o.isCorrect);
if (!hasCorrect) {
return `Question ${i + 1} must have at least one correct answer`;
}
}
return null;
}
router.post('/', (req: AuthenticatedRequest, res: Response) => {
const body = req.body as QuizBody;
const { title, source, aiTopic, questions } = body;
if (!title?.trim() || !source || !questions?.length) {
res.status(400).json({ error: 'Missing required fields: title, source, questions' });
const validationError = validateQuizBody(body);
if (validationError) {
res.status(400).json({ error: validationError });
return;
}
@ -157,6 +190,33 @@ router.put('/:id', (req: AuthenticatedRequest, res: Response) => {
const { title, questions } = body;
const quizId = req.params.id;
if (!title?.trim()) {
res.status(400).json({ error: 'Title is required and cannot be empty' });
return;
}
if (!questions || !Array.isArray(questions) || questions.length === 0) {
res.status(400).json({ error: 'At least one question is required' });
return;
}
for (let i = 0; i < questions.length; i++) {
const q = questions[i];
if (!q.text?.trim()) {
res.status(400).json({ error: `Question ${i + 1} text is required` });
return;
}
if (!q.options || !Array.isArray(q.options) || q.options.length < 2) {
res.status(400).json({ error: `Question ${i + 1} must have at least 2 options` });
return;
}
const hasCorrect = q.options.some(o => o.isCorrect);
if (!hasCorrect) {
res.status(400).json({ error: `Question ${i + 1} must have at least one correct answer` });
return;
}
}
const existing = db.prepare(`
SELECT id FROM quizzes WHERE id = ? AND user_id = ?
`).get(quizId, req.user!.sub);

View file

@ -223,7 +223,10 @@ async function runTests() {
questions: [
{
text: 'Q?',
options: [{ text: 'A', isCorrect: true, shape: 'triangle', color: 'red' }],
options: [
{ text: 'A', isCorrect: true, shape: 'triangle', color: 'red' },
{ text: 'B', isCorrect: false, shape: 'diamond', color: 'blue' },
],
},
],
};
@ -356,6 +359,7 @@ async function runTests() {
timeLimit: 10,
options: [
{ text: 'Solo', isCorrect: true, shape: 'triangle', color: 'red' },
{ text: 'Duo', isCorrect: false, shape: 'diamond', color: 'blue' },
],
},
],
@ -383,7 +387,10 @@ async function runTests() {
questions: [
{
text: 'Timestamp Q?',
options: [{ text: 'A', isCorrect: true, shape: 'triangle', color: 'red' }],
options: [
{ text: 'A', isCorrect: true, shape: 'triangle', color: 'red' },
{ text: 'B', isCorrect: false, shape: 'diamond', color: 'blue' },
],
},
],
};
@ -410,7 +417,10 @@ async function runTests() {
questions: [
{
text: 'Updated Q?',
options: [{ text: 'B', isCorrect: true, shape: 'diamond', color: 'blue' }],
options: [
{ text: 'B', isCorrect: true, shape: 'diamond', color: 'blue' },
{ text: 'C', isCorrect: false, shape: 'circle', color: 'yellow' },
],
},
],
});
@ -469,7 +479,10 @@ async function runTests() {
questions: [
{
text: 'Test?',
options: [{ text: 'A', isCorrect: true, shape: 'triangle', color: 'red' }],
options: [
{ text: 'A', isCorrect: true, shape: 'triangle', color: 'red' },
{ text: 'B', isCorrect: false, shape: 'diamond', color: 'blue' },
],
},
],
};
@ -580,13 +593,13 @@ async function runTests() {
const quiz1 = {
title: 'Concurrent Quiz 1',
source: 'manual',
questions: [{ text: 'Q1?', options: [{ text: 'A', isCorrect: true, shape: 'triangle', color: 'red' }] }],
questions: [{ text: 'Q1?', options: [{ text: 'A', isCorrect: true, shape: 'triangle', color: 'red' }, { text: 'B', isCorrect: false, shape: 'diamond', color: 'blue' }] }],
};
const quiz2 = {
title: 'Concurrent Quiz 2',
source: 'ai_generated',
aiTopic: 'Science',
questions: [{ text: 'Q2?', options: [{ text: 'B', isCorrect: true, shape: 'diamond', color: 'blue' }] }],
questions: [{ text: 'Q2?', options: [{ text: 'C', isCorrect: true, shape: 'circle', color: 'yellow' }, { text: 'D', isCorrect: false, shape: 'square', color: 'green' }] }],
};
const [res1, res2] = await Promise.all([
@ -621,7 +634,7 @@ async function runTests() {
const quiz = {
title: longTitle,
source: 'manual',
questions: [{ text: 'Q?', options: [{ text: 'A', isCorrect: true, shape: 'triangle', color: 'red' }] }],
questions: [{ text: 'Q?', options: [{ text: 'A', isCorrect: true, shape: 'triangle', color: 'red' }, { text: 'B', isCorrect: false, shape: 'diamond', color: 'blue' }] }],
};
const { data } = await request('POST', '/api/quizzes', quiz, 201);
@ -640,7 +653,7 @@ async function runTests() {
const quiz = {
title: specialTitle,
source: 'manual',
questions: [{ text: 'Q?', options: [{ text: 'A', isCorrect: true, shape: 'triangle', color: 'red' }] }],
questions: [{ text: 'Q?', options: [{ text: 'A', isCorrect: true, shape: 'triangle', color: 'red' }, { text: 'B', isCorrect: false, shape: 'diamond', color: 'blue' }] }],
};
const { data } = await request('POST', '/api/quizzes', quiz, 201);
@ -658,12 +671,327 @@ async function runTests() {
const quiz = {
title: ' ',
source: 'manual',
questions: [{ text: 'Q?', options: [{ text: 'A', isCorrect: true, shape: 'triangle', color: 'red' }] }],
questions: [{ text: 'Q?', options: [{ text: 'A', isCorrect: true, shape: 'triangle', color: 'red' }, { text: 'B', isCorrect: false, shape: 'diamond', color: 'blue' }] }],
};
await request('POST', '/api/quizzes', quiz, 400);
});
console.log('\nPhase 6 - Error Handling Tests:');
await test('POST /api/quizzes with question without text returns 400', async () => {
const invalidQuiz = {
title: 'Quiz with empty question',
source: 'manual',
questions: [
{
text: '',
options: [
{ text: 'A', isCorrect: true, shape: 'triangle', color: 'red' },
{ text: 'B', isCorrect: false, shape: 'diamond', color: 'blue' },
],
},
],
};
await request('POST', '/api/quizzes', invalidQuiz, 400);
});
await test('POST /api/quizzes with question with only one option returns 400', async () => {
const invalidQuiz = {
title: 'Quiz with single option',
source: 'manual',
questions: [
{
text: 'Question with one option?',
options: [
{ text: 'Only one', isCorrect: true, shape: 'triangle', color: 'red' },
],
},
],
};
await request('POST', '/api/quizzes', invalidQuiz, 400);
});
await test('POST /api/quizzes with question with no correct answer returns 400', async () => {
const invalidQuiz = {
title: 'Quiz with no correct answer',
source: 'manual',
questions: [
{
text: 'Question with no correct?',
options: [
{ text: 'A', isCorrect: false, shape: 'triangle', color: 'red' },
{ text: 'B', isCorrect: false, shape: 'diamond', color: 'blue' },
],
},
],
};
await request('POST', '/api/quizzes', invalidQuiz, 400);
});
await test('POST /api/quizzes with invalid source type returns 400', async () => {
const invalidQuiz = {
title: 'Quiz with invalid source',
source: 'invalid_source_type',
questions: [
{
text: 'Question?',
options: [
{ text: 'A', isCorrect: true, shape: 'triangle', color: 'red' },
{ text: 'B', isCorrect: false, shape: 'diamond', color: 'blue' },
],
},
],
};
await request('POST', '/api/quizzes', invalidQuiz, 400);
});
await test('POST /api/quizzes with null questions returns 400', async () => {
const invalidQuiz = {
title: 'Quiz with null questions',
source: 'manual',
questions: null,
};
await request('POST', '/api/quizzes', invalidQuiz, 400);
});
await test('POST /api/quizzes with question missing options returns 400', async () => {
const invalidQuiz = {
title: 'Quiz missing options',
source: 'manual',
questions: [
{
text: 'Question without options?',
},
],
};
await request('POST', '/api/quizzes', invalidQuiz, 400);
});
await test('PUT /api/quizzes/:id with invalid data returns 400', async () => {
const validQuiz = {
title: 'Valid Quiz for Update Test',
source: 'manual',
questions: [
{
text: 'Valid question?',
options: [
{ text: 'A', isCorrect: true, shape: 'triangle', color: 'red' },
{ text: 'B', isCorrect: false, shape: 'diamond', color: 'blue' },
],
},
],
};
const { data } = await request('POST', '/api/quizzes', validQuiz, 201);
const quizId = (data as { id: string }).id;
const invalidUpdate = {
title: '',
questions: [],
};
await request('PUT', `/api/quizzes/${quizId}`, invalidUpdate, 400);
await request('DELETE', `/api/quizzes/${quizId}`, undefined, 204);
});
console.log('\nPhase 6 - Malformed Request Tests:');
await test('POST /api/quizzes with malformed JSON returns 400', async () => {
const res = await fetch(`${API_URL}/api/quizzes`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${TOKEN}`,
},
body: '{ invalid json }',
});
if (res.status !== 400) throw new Error(`Expected 400, got ${res.status}`);
});
await test('GET /api/quizzes/:id with very long ID returns 404', async () => {
const longId = 'a'.repeat(1000);
await request('GET', `/api/quizzes/${longId}`, undefined, 404);
});
await test('DELETE /api/quizzes/:id with SQL injection attempt returns 404', async () => {
const maliciousId = "'; DROP TABLE quizzes; --";
await request('DELETE', `/api/quizzes/${encodeURIComponent(maliciousId)}`, undefined, 404);
});
console.log('\nPhase 6 - Content Type Tests:');
await test('POST /api/quizzes without Content-Type still works with JSON body', async () => {
const quiz = {
title: 'No Content-Type Quiz',
source: 'manual',
questions: [
{
text: 'Question?',
options: [
{ text: 'A', isCorrect: true, shape: 'triangle', color: 'red' },
{ text: 'B', isCorrect: false, shape: 'diamond', color: 'blue' },
],
},
],
};
const res = await fetch(`${API_URL}/api/quizzes`, {
method: 'POST',
headers: {
Authorization: `Bearer ${TOKEN}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(quiz),
});
if (res.status !== 201) throw new Error(`Expected 201, got ${res.status}`);
const data = await res.json();
await request('DELETE', `/api/quizzes/${data.id}`, undefined, 204);
});
console.log('\nPhase 6 - Boundary Tests:');
await test('POST /api/quizzes with many questions succeeds', async () => {
const manyQuestions = Array.from({ length: 50 }, (_, i) => ({
text: `Question ${i + 1}?`,
timeLimit: 20,
options: [
{ text: `A${i}`, isCorrect: true, shape: 'triangle', color: 'red' },
{ text: `B${i}`, isCorrect: false, shape: 'diamond', color: 'blue' },
],
}));
const quiz = {
title: '50 Question Quiz',
source: 'manual',
questions: manyQuestions,
};
const { data } = await request('POST', '/api/quizzes', quiz, 201);
const quizId = (data as { id: string }).id;
const { data: getResult } = await request('GET', `/api/quizzes/${quizId}`);
const savedQuiz = getResult as { questions: unknown[] };
if (savedQuiz.questions.length !== 50) {
throw new Error(`Expected 50 questions, got ${savedQuiz.questions.length}`);
}
await request('DELETE', `/api/quizzes/${quizId}`, undefined, 204);
});
await test('POST /api/quizzes with many options per question succeeds', async () => {
const manyOptions = Array.from({ length: 10 }, (_, i) => ({
text: `Option ${i + 1}`,
isCorrect: i === 0,
shape: 'triangle',
color: 'red',
}));
const quiz = {
title: '10 Options Quiz',
source: 'manual',
questions: [
{
text: 'Question with 10 options?',
options: manyOptions,
},
],
};
const { data } = await request('POST', '/api/quizzes', quiz, 201);
const quizId = (data as { id: string }).id;
const { data: getResult } = await request('GET', `/api/quizzes/${quizId}`);
const savedQuiz = getResult as { questions: { options: unknown[] }[] };
if (savedQuiz.questions[0].options.length !== 10) {
throw new Error(`Expected 10 options, got ${savedQuiz.questions[0].options.length}`);
}
await request('DELETE', `/api/quizzes/${quizId}`, undefined, 204);
});
await test('POST /api/quizzes with unicode characters in all fields', async () => {
const unicodeQuiz = {
title: 'Emoji Quiz title test',
source: 'manual',
aiTopic: 'Japanese test',
questions: [
{
text: 'What is this character?',
timeLimit: 30,
options: [
{ text: 'Option A', isCorrect: true, shape: 'triangle', color: 'red', reason: 'Because Emoji test!' },
{ text: 'Chinese characters', isCorrect: false, shape: 'diamond', color: 'blue' },
],
},
],
};
const { data } = await request('POST', '/api/quizzes', unicodeQuiz, 201);
const quizId = (data as { id: string }).id;
const { data: getResult } = await request('GET', `/api/quizzes/${quizId}`);
const savedQuiz = getResult as { title: string; questions: { text: string; options: { text: string }[] }[] };
if (savedQuiz.title !== 'Emoji Quiz title test') throw new Error('Unicode title not preserved');
if (savedQuiz.questions[0].text !== 'What is this character?') throw new Error('Unicode question not preserved');
if (savedQuiz.questions[0].options[1].text !== 'Chinese characters') throw new Error('Unicode option not preserved');
await request('DELETE', `/api/quizzes/${quizId}`, undefined, 204);
});
console.log('\nPhase 6 - Duplicate/Idempotency Tests:');
await test('POST /api/quizzes with same data creates separate quizzes', async () => {
const quiz = {
title: 'Duplicate Test Quiz',
source: 'manual',
questions: [
{
text: 'Same question?',
options: [
{ text: 'A', isCorrect: true, shape: 'triangle', color: 'red' },
{ text: 'B', isCorrect: false, shape: 'diamond', color: 'blue' },
],
},
],
};
const { data: data1 } = await request('POST', '/api/quizzes', quiz, 201);
const { data: data2 } = await request('POST', '/api/quizzes', quiz, 201);
const id1 = (data1 as { id: string }).id;
const id2 = (data2 as { id: string }).id;
if (id1 === id2) throw new Error('Duplicate POST should create separate quizzes with unique IDs');
await request('DELETE', `/api/quizzes/${id1}`, undefined, 204);
await request('DELETE', `/api/quizzes/${id2}`, undefined, 204);
});
await test('DELETE /api/quizzes/:id twice returns 404 on second call', async () => {
const quiz = {
title: 'Double Delete Quiz',
source: 'manual',
questions: [
{
text: 'Q?',
options: [
{ text: 'A', isCorrect: true, shape: 'triangle', color: 'red' },
{ text: 'B', isCorrect: false, shape: 'diamond', color: 'blue' },
],
},
],
};
const { data } = await request('POST', '/api/quizzes', quiz, 201);
const quizId = (data as { id: string }).id;
await request('DELETE', `/api/quizzes/${quizId}`, undefined, 204);
await request('DELETE', `/api/quizzes/${quizId}`, undefined, 404);
});
console.log('\n=== Results ===');
const passed = results.filter((r) => r.passed).length;
const failed = results.filter((r) => !r.passed).length;