|
| 1 | +import { Dictionary, TraceoOptions } from "../types/client"; |
| 2 | +import { RequestOptions } from "../types/transport"; |
| 3 | +import { FetchTransport } from "./fetch"; |
| 4 | +import { XhrTransport } from "./xhr"; |
| 5 | + |
| 6 | +export class Transport { |
| 7 | + private _options: TraceoOptions; |
| 8 | + |
| 9 | + constructor(options: TraceoOptions) { |
| 10 | + this._options = options; |
| 11 | + } |
| 12 | + |
| 13 | + public send(body: object, headers: Dictionary<string>) { |
| 14 | + try { |
| 15 | + const options = this.requestOptions(body, headers); |
| 16 | + this.transport(options).request(); |
| 17 | + } catch (error) { |
| 18 | + console.log("Error sending data to traceo: ", error); |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + private transport(options: RequestOptions) { |
| 23 | + if (window.XMLHttpRequest && !window.fetch) { |
| 24 | + return new XhrTransport(options); |
| 25 | + } |
| 26 | + |
| 27 | + return new FetchTransport(options); |
| 28 | + } |
| 29 | + |
| 30 | + private requestOptions(body: {}, headers: Dictionary<string>): RequestOptions { |
| 31 | + const reqUrl = this.clientURL; |
| 32 | + |
| 33 | + // http://localhost:3000/api/worker/incident/app-id |
| 34 | + const url = `${reqUrl.origin}/api/worker/incident/${this._options.appId}`; |
| 35 | + |
| 36 | + return { |
| 37 | + protocol: reqUrl.protocol, |
| 38 | + headers: { |
| 39 | + "Content-Type": "application/json", |
| 40 | + ...headers |
| 41 | + }, |
| 42 | + host: reqUrl.hostname, |
| 43 | + method: "POST", |
| 44 | + url, |
| 45 | + port: reqUrl.port, |
| 46 | + body |
| 47 | + }; |
| 48 | + } |
| 49 | + |
| 50 | + private get clientURL(): URL { |
| 51 | + return new URL(this._options.url); |
| 52 | + } |
| 53 | +} |
0 commit comments