|
| 1 | +// Copyright (C) 2024 CVAT.ai Corporation |
| 2 | +// |
| 3 | +// SPDX-License-Identifier: MIT |
| 4 | + |
| 5 | +import Axios, { AxiosRequestConfig, AxiosResponse } from 'axios'; |
| 6 | +import * as tus from 'tus-js-client'; |
| 7 | + |
| 8 | +class AxiosHttpResponse implements tus.HttpResponse { |
| 9 | + readonly #axiosResponse: AxiosResponse; |
| 10 | + |
| 11 | + constructor(axiosResponse: AxiosResponse) { |
| 12 | + this.#axiosResponse = axiosResponse; |
| 13 | + } |
| 14 | + |
| 15 | + getStatus(): number { return this.#axiosResponse.status; } |
| 16 | + getHeader(header: string): string { return this.#axiosResponse.headers[header.toLowerCase()]; } |
| 17 | + getBody(): string { return this.#axiosResponse.data; } |
| 18 | + getUnderlyingObject(): any { return this.#axiosResponse; } |
| 19 | +} |
| 20 | + |
| 21 | +class AxiosHttpRequest implements tus.HttpRequest { |
| 22 | + readonly #axiosConfig: AxiosRequestConfig; |
| 23 | + readonly #abortController: AbortController; |
| 24 | + |
| 25 | + constructor(method: string, url: string) { |
| 26 | + this.#abortController = new AbortController(); |
| 27 | + this.#axiosConfig = { |
| 28 | + method, url, headers: {}, signal: this.#abortController.signal, |
| 29 | + }; |
| 30 | + } |
| 31 | + |
| 32 | + getMethod(): string { return this.#axiosConfig.method; } |
| 33 | + getURL(): string { return this.#axiosConfig.url; } |
| 34 | + |
| 35 | + setHeader(header: string, value: string): void { |
| 36 | + this.#axiosConfig.headers[header.toLowerCase()] = value; |
| 37 | + } |
| 38 | + getHeader(header: string): string | undefined { |
| 39 | + return this.#axiosConfig.headers[header.toLowerCase()]; |
| 40 | + } |
| 41 | + |
| 42 | + setProgressHandler(handler: (bytesSent: number) => void): void { |
| 43 | + this.#axiosConfig.onUploadProgress = (progressEvent) => { |
| 44 | + handler(progressEvent.loaded); |
| 45 | + }; |
| 46 | + } |
| 47 | + |
| 48 | + async send(body: any): Promise<tus.HttpResponse> { |
| 49 | + const axiosResponse = await Axios({ ...this.#axiosConfig, data: body }); |
| 50 | + return new AxiosHttpResponse(axiosResponse); |
| 51 | + } |
| 52 | + |
| 53 | + async abort(): Promise<void> { this.#abortController.abort(); } |
| 54 | + |
| 55 | + getUnderlyingObject(): any { return this.#axiosConfig; } |
| 56 | +} |
| 57 | + |
| 58 | +class AxiosHttpStack implements tus.HttpStack { |
| 59 | + createRequest(method: string, url: string): tus.HttpRequest { |
| 60 | + return new AxiosHttpRequest(method, url); |
| 61 | + } |
| 62 | + getName(): string { return 'AxiosHttpStack'; } |
| 63 | +} |
| 64 | + |
| 65 | +export const axiosTusHttpStack = new AxiosHttpStack(); |
0 commit comments