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

autocomplete-mock.interceptor.ts

51 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 autocompleteMockInterceptor: HttpInterceptorFn = (
7 req,
8 next,
9): Observable<HttpEvent<unknown>> => {
10 const { url } = req
11​
12 if (url.includes('/api/autocomplete')) {
13 const term = new URLSearchParams(req.url.split('?')[1]).get('term') || ''
14​
15 const data = [
16 'C#',
17 'C++',
18 'Go',
19 'Java',
20 'JavaScript',
21 'Kotlin',
22 'Lisp',
23 'Objective-C',
24 'PHP',
25 'Perl',
26 'Python',
27 'R',
28 'Ruby',
29 'Rust',
30 'SQL',
31 'Scala',
32 'Shell',
33 'Swift',
34 'TypeScript',
35 ]
36​
37 // Simulate network latency with a random delay between 100ms and 500ms
38 const delayDuration = Math.random() * (500 - 100) + 100
39 return of(
40 new HttpResponse({
41 status: 200,
42 body: {
43 suggestions: data.filter((item) =>
44 item.toLowerCase().startsWith(term.toLowerCase()),
45 ),
46 },
47 }),
48 ).pipe(delayWhen(() => timer(delayDuration)))
49 }
50 return next(req)