Open History to see the last commit
1/**
2 * MockApiInterceptor is used to simulate API responses for `/api/tasks` endpoints.
3 * It handles the following operations:
4 * - GET: Fetches all tasks from localStorage.
5 * - POST: Adds a new task to localStorage.
6 * - DELETE: Clears all tasks from localStorage.
7 * Simulated responses include a delay to mimic network latency.
8 */
9import { HttpResponse } from '@angular/common/http'
10import { delay, of } from 'rxjs'
11import type {
12 HttpEvent,
13 HttpHandlerFn,
14 HttpInterceptorFn,
15 HttpRequest,
16} from '@angular/common/http'
17import type { Observable } from 'rxjs'
18β
19export const mockInterceptor: HttpInterceptorFn = (
20 req: HttpRequest<unknown>,
21 next: HttpHandlerFn,
22): Observable<HttpEvent<any>> => {
23 const respondWith = (status: number, body: any) =>
24 of(new HttpResponse({ status, body })).pipe(delay(100))
25 if (req.url === '/api/tasks') {
26 switch (req.method) {
27 case 'GET':
28 return respondWith(
29 200,
30 JSON.parse(localStorage.getItem('tasks') || '[]'),
31 )
32 case 'POST':
33 const tasks = JSON.parse(localStorage.getItem('tasks') || '[]')
34 tasks.push(req.body)
35 localStorage.setItem('tasks', JSON.stringify(tasks))
36 return respondWith(201, {
37 status: 'success',
38 task: req.body,
39 })
40 case 'DELETE':
41 localStorage.removeItem('tasks')
42 return respondWith(200, { status: 'success' })
43 }
44 }
45 return next(req)
46}