|
1 | 1 | import { Logger } from 'simple-logging-system'; |
2 | | -import { HttpRequest, HttpClient } from 'simple-http-request-builder'; |
| 2 | +import { |
| 3 | + HttpRequest, |
| 4 | + HttpClient, |
| 5 | + HttpMethod, |
| 6 | +} from 'simple-http-request-builder'; |
3 | 7 | import { |
4 | 8 | genericError, |
5 | 9 | HttpResponse, |
6 | 10 | toErrorResponsePromise, |
7 | 11 | networkError, |
8 | 12 | timeoutError, |
9 | 13 | } from './HttpResponse'; |
| 14 | +import { HttpPromise, unwrapHttpPromise } from '../promise/HttpPromise'; |
10 | 15 |
|
11 | 16 | const logger = new Logger('FetchClient'); |
12 | 17 |
|
@@ -113,3 +118,36 @@ export const fetchClient = <T = Response>(httpRequest: HttpRequest<unknown>, ... |
113 | 118 | return { response }; |
114 | 119 | }) |
115 | 120 | .catch(networkErrorCatcher); |
| 121 | + |
| 122 | +/** |
| 123 | + * A {@link HttpClient} that uses {@link HttpRequest} and returns a `Promise<HttpResponse<T>>`. |
| 124 | + * |
| 125 | + * This is used by {@link createHttpFetchRequest} to make fetch requests. |
| 126 | + * |
| 127 | + * Common clients are: |
| 128 | + * - {@link defaultJsonFetchClient} for REST JSON API |
| 129 | + * - raw {@link fetchClient} for non-JSON API (so often just for binary content) |
| 130 | + */ |
| 131 | +export type HttpFetchClient = <T>(httpRequest: HttpRequest<unknown>) => Promise<HttpResponse<T>>; |
| 132 | + |
| 133 | +/** |
| 134 | + * Factory function to create fetch {@link HttpRequest}. |
| 135 | + * |
| 136 | + * @param baseUrl The base URL. It should not contain an ending slash. A valid base URL is: http://hostname/api |
| 137 | + * @param method The HTTP method used for the request, see {@link HttpMethod} |
| 138 | + * @param path The path of the endpoint to call, it should be composed with a leading slash |
| 139 | + * and will be appended to the {@link HttpRequest#baseUrl}. A valid path is: /users |
| 140 | + * @param httpClient The fetch client that uses {@link HttpRequest} and returns a `Promise<HttpResponse<T>>` |
| 141 | + */ |
| 142 | +export const createHttpFetchRequest = <T>( |
| 143 | + baseUrl: string, method: HttpMethod, path: string, httpClient: HttpFetchClient, |
| 144 | +) |
| 145 | + : HttpRequest<HttpPromise<T>> => new HttpRequest<HttpPromise<T>>( |
| 146 | + (httpRequest) => new HttpPromise<T>( |
| 147 | + unwrapHttpPromise(httpClient(httpRequest)), |
| 148 | + httpRequest, |
| 149 | + ), |
| 150 | + baseUrl, |
| 151 | + method, |
| 152 | + path, |
| 153 | + ); |
0 commit comments