<script>
import { of, fromEvent } from 'rxjs'
import { fromFetch } from 'rxjs/fetch'
import {
map,
concatMap,
catchError,
switchMap,
startWith,
debounceTime,
} from 'rxjs/operators'
import { onMount$ } from 'svelte-rx'
let inputElement
const books$ = onMount$.pipe(
concatMap(() =>
fromEvent(inputElement, 'input').pipe(
debounceTime(350),
map(e => e.target.value),
switchMap(query => {
if (!query) {
return of([])
}
return fromFetch(
`https://www.episodate.com/api/search?q=${query}&page=1`,
).pipe(
switchMap(response => {
if (response.ok) {
return response.json()
} else {
return of({ error: true, message: `Error ${response.status}` })
}
}),
catchError(err => of({ error: true, message: err.message })),
)