| 1 |
import { createOperatorSubscriber } from '../../operators/OperatorSubscriber'; |
| 2 |
import { Observable } from '../../Observable'; |
| 3 |
import { innerFrom } from '../../observable/innerFrom'; |
| 4 |
import { ObservableInput } from '../../types'; |
| 5 |
|
| 6 |
export function fromFetch<T>( |
| 7 |
input: string | Request, |
| 8 |
init: RequestInit & { |
| 9 |
selector: (response: Response) => ObservableInput<T>; |
| 10 |
} |
| 11 |
): Observable<T>; |
| 12 |
|
| 13 |
export function fromFetch(input: string | Request, init?: RequestInit): Observable<Response>; |
| 14 |
|
| 15 |
/** |
| 16 |
* Uses [the Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) to |
| 17 |
* make an HTTP request. |
| 18 |
* |
| 19 |
* **WARNING** Parts of the fetch API are still experimental. `AbortController` is |
| 20 |
* required for this implementation to work and use cancellation appropriately. |
| 21 |
* |
| 22 |
* Will automatically set up an internal [AbortController](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) |
| 23 |
* in order to finalize the internal `fetch` when the subscription tears down. |
| 24 |
* |
| 25 |
* If a `signal` is provided via the `init` argument, it will behave like it usually does with |
| 26 |
* `fetch`. If the provided `signal` aborts, the error that `fetch` normally rejects with |
| 27 |
* in that scenario will be emitted as an error from the observable. |
| 28 |
* |
| 29 |
* ## Examples |
| 30 |
* |
| 31 |
* Basic use |
| 32 |
* |
| 33 |
* ```ts |
| 34 |
* import { fromFetch } from 'rxjs/fetch'; |
| 35 |
* import { switchMap, of, catchError } from 'rxjs'; |
| 36 |
* |
| 37 |
* const data$ = fromFetch('https://api.github.com/users?per_page=5').pipe( |
| 38 |
* switchMap(response => { |
| 39 |
* if (response.ok) { |
| 40 |
* // OK return data |
| 41 |
* return response.json(); |
| 42 |
* } else { |
| 43 |
* // Server is returning a status requiring the client to try something else. |
| 44 |
* return of({ error: true, message: `Error ${ response.status }` }); |
| 45 |
* } |
| 46 |
* }), |
| 47 |
* catchError(err => { |
| 48 |
* // Network or other error, handle appropriately |
| 49 |
* console.error(err); |
| 50 |
* return of({ error: true, message: err.message }) |
| 51 |
* }) |
| 52 |
* ); |
| 53 |
* |
| 54 |
* data$.subscribe({ |
| 55 |
* next: result => console.log(result), |
| 56 |
* complete: () => console.log('done') |
| 57 |
* }); |
| 58 |
* ``` |
| 59 |
* |
| 60 |
* ### Use with Chunked Transfer Encoding |
| 61 |
* |
| 62 |
* With HTTP responses that use [chunked transfer encoding](https://tools.ietf.org/html/rfc7230#section-3.3.1), |
| 63 |
* the promise returned by `fetch` will resolve as soon as the response's headers are |
| 64 |
* received. |
| 65 |
* |
| 66 |
* That means the `fromFetch` observable will emit a `Response` - and will |
| 67 |
* then complete - before the body is received. When one of the methods on the |
| 68 |
* `Response` - like `text()` or `json()` - is called, the returned promise will not |
| 69 |
* resolve until the entire body has been received. Unsubscribing from any observable |
| 70 |
* that uses the promise as an observable input will not abort the request. |
| 71 |
* |
| 72 |
* To facilitate aborting the retrieval of responses that use chunked transfer encoding, |
| 73 |
* a `selector` can be specified via the `init` parameter: |
| 74 |
* |
| 75 |
* ```ts |
| 76 |
* import { of } from 'rxjs'; |
| 77 |
* import { fromFetch } from 'rxjs/fetch'; |
| 78 |
* |
| 79 |
* const data$ = fromFetch('https://api.github.com/users?per_page=5', { |
| 80 |
* selector: response => response.json() |
| 81 |
* }); |
| 82 |
* |
| 83 |
* data$.subscribe({ |
| 84 |
* next: result => console.log(result), |
| 85 |
* complete: () => console.log('done') |
| 86 |
* }); |
| 87 |
* ``` |
| 88 |
* |
| 89 |
* @param input The resource you would like to fetch. Can be a url or a request object. |
| 90 |
* @param initWithSelector A configuration object for the fetch. |
| 91 |
* [See MDN for more details](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters) |
| 92 |
* @returns An Observable, that when subscribed to, performs an HTTP request using the native `fetch` |
| 93 |
* function. The {@link Subscription} is tied to an `AbortController` for the fetch. |
| 94 |
*/ |
| 95 |
export function fromFetch<T>( |
| 96 |
input: string | Request, |
| 97 |
initWithSelector: RequestInit & { |
| 98 |
selector?: (response: Response) => ObservableInput<T>; |
| 99 |
} = {} |
| 100 |
): Observable<Response | T> { |
| 101 |
const { selector, ...init } = initWithSelector; |
| 102 |
return new Observable<Response | T>((subscriber) => { |
| 103 |
// Our controller for aborting this fetch. |
| 104 |
// Any externally provided AbortSignal will have to call |
| 105 |
// abort on this controller when signaled, because the |
| 106 |
// signal from this controller is what is being passed to `fetch`. |
| 107 |
const controller = new AbortController(); |
| 108 |
const { signal } = controller; |
| 109 |
// This flag exists to make sure we don't `abort()` the fetch upon tearing down |
| 110 |
// this observable after emitting a Response. Aborting in such circumstances |
| 111 |
// would also abort subsequent methods - like `json()` - that could be called |
| 112 |
// on the Response. Consider: `fromFetch().pipe(take(1), mergeMap(res => res.json()))` |
| 113 |
let abortable = true; |
| 114 |
|
| 115 |
// If the user provided an init configuration object, |
| 116 |
// let's process it and chain our abort signals, if necessary. |
| 117 |
// If a signal is provided, just have it finalized. It's a cancellation token, basically. |
| 118 |
const { signal: outerSignal } = init; |
| 119 |
if (outerSignal) { |
| 120 |
if (outerSignal.aborted) { |
| 121 |
controller.abort(); |
| 122 |
} else { |
| 123 |
// We got an AbortSignal from the arguments passed into `fromFetch`. |
| 124 |
// We need to wire up our AbortController to abort when this signal aborts. |
| 125 |
const outerSignalHandler = () => { |
| 126 |
if (!signal.aborted) { |
| 127 |
controller.abort(); |
| 128 |
} |
| 129 |
}; |
| 130 |
outerSignal.addEventListener('abort', outerSignalHandler); |
| 131 |
subscriber.add(() => outerSignal.removeEventListener('abort', outerSignalHandler)); |
| 132 |
} |
| 133 |
} |
| 134 |
|
| 135 |
// The initialization object passed to `fetch` as the second |
| 136 |
// argument. This ferries in important information, including our |
| 137 |
// AbortSignal. Create a new init, so we don't accidentally mutate the |
| 138 |
// passed init, or reassign it. This is because the init passed in |
| 139 |
// is shared between each subscription to the result. |
| 140 |
const perSubscriberInit: RequestInit = { ...init, signal }; |
| 141 |
|
| 142 |
const handleError = (err: any) => { |
| 143 |
abortable = false; |
| 144 |
subscriber.error(err); |
| 145 |
}; |
| 146 |
|
| 147 |
fetch(input, perSubscriberInit) |
| 148 |
.then((response) => { |
| 149 |
if (selector) { |
| 150 |
// If we have a selector function, use it to project our response. |
| 151 |
// Note that any error that comes from our selector will be |
| 152 |
// sent to the promise `catch` below and handled. |
| 153 |
innerFrom(selector(response)).subscribe( |
| 154 |
createOperatorSubscriber( |
| 155 |
subscriber, |
| 156 |
// Values are passed through to the subscriber |
| 157 |
undefined, |
| 158 |
// The projected response is complete. |
| 159 |
() => { |
| 160 |
abortable = false; |
| 161 |
subscriber.complete(); |
| 162 |
}, |
| 163 |
handleError |
| 164 |
) |
| 165 |
); |
| 166 |
} else { |
| 167 |
abortable = false; |
| 168 |
subscriber.next(response); |
| 169 |
subscriber.complete(); |
| 170 |
} |
| 171 |
}) |
| 172 |
.catch(handleError); |
| 173 |
|
| 174 |
return () => { |
| 175 |
if (abortable) { |
| 176 |
controller.abort(); |
| 177 |
} |
| 178 |
}; |
| 179 |
}); |
| 180 |
} |