DefaultHttpClient.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. import { AbortError } from "./Errors";
  4. import { FetchHttpClient } from "./FetchHttpClient";
  5. import { HttpClient, HttpRequest, HttpResponse } from "./HttpClient";
  6. import { ILogger } from "./ILogger";
  7. import { Platform } from "./Utils";
  8. import { XhrHttpClient } from "./XhrHttpClient";
  9. /** Default implementation of {@link @microsoft/signalr.HttpClient}. */
  10. export class DefaultHttpClient extends HttpClient {
  11. private readonly _httpClient: HttpClient;
  12. /** Creates a new instance of the {@link @microsoft/signalr.DefaultHttpClient}, using the provided {@link @microsoft/signalr.ILogger} to log messages. */
  13. public constructor(logger: ILogger) {
  14. super();
  15. if (typeof fetch !== "undefined" || Platform.isNode) {
  16. this._httpClient = new FetchHttpClient(logger);
  17. } else if (typeof XMLHttpRequest !== "undefined") {
  18. this._httpClient = new XhrHttpClient(logger);
  19. } else {
  20. throw new Error("No usable HttpClient found.");
  21. }
  22. }
  23. /** @inheritDoc */
  24. public send(request: HttpRequest): Promise<HttpResponse> {
  25. // Check that abort was not signaled before calling send
  26. if (request.abortSignal && request.abortSignal.aborted) {
  27. return Promise.reject(new AbortError());
  28. }
  29. if (!request.method) {
  30. return Promise.reject(new Error("No method defined."));
  31. }
  32. if (!request.url) {
  33. return Promise.reject(new Error("No url defined."));
  34. }
  35. return this._httpClient.send(request);
  36. }
  37. public getCookieString(url: string): string {
  38. return this._httpClient.getCookieString(url);
  39. }
  40. }