Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

projects-mock.interceptor.ts

45 lines1.2 KB

1import { HttpResponse } from '@angular/common/http'
2import { delayWhen, of, timer } from 'rxjs'
3import type { Observable } from 'rxjs'
4import type { HttpEvent, HttpInterceptorFn } from '@angular/common/http'
5​
6export const projectsMockInterceptor: HttpInterceptorFn = (
7 req,
8 next,
9): Observable<HttpEvent<unknown>> => {
10 const { url } = req
11​
12 if (url.includes('/api/projects')) {
13 const cursor = parseInt(
14 new URLSearchParams(req.url.split('?')[1]).get('cursor') || '0',
15 10,
16 )
17 const pageSize = 4
18​
19 const data = Array(pageSize)
20 .fill(0)
21 .map((_, i) => {
22 return {
23 name: 'Project ' + (i + cursor) + ` (server time: ${Date.now()})`,
24 id: i + cursor,
25 }
26 })
27​
28 const nextId = cursor < 20 ? data[data.length - 1].id + 1 : null
29 const previousId = cursor > -20 ? data[0].id - pageSize : null
30​
31 // Simulate network latency with a random delay between 100ms and 500ms
32 const delayDuration = Math.random() * (500 - 100) + 100
33 return of(
34 new HttpResponse({
35 status: 200,
36 body: {
37 data,
38 nextId,
39 previousId,
40 },
41 }),
42 ).pipe(delayWhen(() => timer(delayDuration)))
43 }
44 return next(req)