1+ import * as http from "http" ;
2+ import * as https from "https" ;
3+ import { RequestType , RequestOptionsType } from "./types" ;
4+ import { getGlobalTraceo } from "./utils" ;
5+
6+ const requestWriteBody = ( method : RequestType , request : http . ClientRequest , body : { } ) => {
7+ if ( method === "POST" ) {
8+ request . write ( JSON . stringify ( body ) ) ;
9+ }
10+ }
11+
12+ const requestModule = ( ) : typeof http | typeof https => {
13+ const protocol = clientURL ( ) . protocol ;
14+ return protocol == "http:" ? http : https ;
15+ }
16+
17+ const clientURL = ( ) : URL => {
18+ return new URL ( getGlobalTraceo ( ) . options . host ) ;
19+ }
20+
21+ const requestOptions = ( url : string , method : RequestType ) : http . RequestOptions => {
22+ const host = getGlobalTraceo ( ) . options . host ;
23+ const reqUrl = new URL ( host ) ;
24+ const path = new URL ( url , host ) ;
25+
26+ return {
27+ protocol : reqUrl . protocol ,
28+ port : reqUrl . port ,
29+ host : reqUrl . hostname ,
30+ method,
31+ path : path . pathname
32+ } ;
33+ }
34+
35+ const requestHeaders = ( method : RequestType ) => {
36+ const headers = getGlobalTraceo ( ) . headers ;
37+
38+ if ( method !== "POST" ) return headers ;
39+ return {
40+ headers : {
41+ "Content-Type" : "application/json" ,
42+ ...headers
43+ }
44+ } ;
45+ }
46+
47+ /**
48+ * Make http/s request to Traceo platoform.
49+ *
50+ * Default request method is POST, in this case in hedaers is passed "Content-Type": "application/json".
51+ * URL is concatenation of passed host to client and pathanme to this method.
52+ * Use callback/onError callbacks to handle action after operation.
53+ */
54+ const request = ( { url, method = "POST" , body, onError, callback } : RequestOptionsType ) => {
55+ const options = {
56+ ...requestHeaders ( method ) ,
57+ ...requestOptions ( url , method )
58+ } ;
59+
60+ const httpModule = requestModule ( ) ;
61+
62+ const request = httpModule . request ( options , callback ) ;
63+ request . on ( "error" , ( ) => onError ) ;
64+
65+ requestWriteBody ( method , request , body ) ;
66+
67+ request . end ( ) ;
68+ }
69+
70+ export const transport = {
71+ request
72+ }
0 commit comments