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 sessionStorage.
5 * - POST: Adds a new task to sessionStorage.
6 * Simulated responses include a delay to mimic network latency.
7 */
8import { HttpErrorResponse, HttpResponse } from '@angular/common/http'
9import { delay, of, switchMap, throwError, timer } from 'rxjs'
10import type {
11 HttpEvent,
12 HttpHandlerFn,
13 HttpInterceptorFn,
14 HttpRequest,
15} from '@angular/common/http'
16import type { Observable } from 'rxjs'
17β
18export const mockInterceptor: HttpInterceptorFn = (
19 req: HttpRequest<unknown>,
20 next: HttpHandlerFn,
21): Observable<HttpEvent<unknown>> => {
22 const respondWith = (status: number, body: unknown) =>
23 of(new HttpResponse({ status, body })).pipe(delay(1000))
24 if (req.url === '/api/tasks') {
25 switch (req.method) {
26 case 'GET':
27 return respondWith(
28 200,
29 JSON.parse(
30 sessionStorage.getItem('optimistic-updates-tasks') || '[]',
31 ),
32 )
33 case 'POST': {
34 const tasks = JSON.parse(
35 sessionStorage.getItem('optimistic-updates-tasks') || '[]',
36 )
37 tasks.push(req.body)
38 sessionStorage.setItem(
39 'optimistic-updates-tasks',
40 JSON.stringify(tasks),
41 )
42 return respondWith(201, {
43 status: 'success',
44 task: req.body,
45 })
46 }
47 }
48 }
49 if (req.url === '/api/tasks-wrong-url') {
50 return timer(1000).pipe(
51 switchMap(() =>
52 throwError(
53 () =>
54 new HttpErrorResponse({
55 status: 500,
56 url: req.url,
57 error: { status: 'error' },
58 }),
59 ),
60 ),
61 )
62 }
63β
64 return next(req)
65}