-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtracking.js
More file actions
103 lines (96 loc) · 3.11 KB
/
tracking.js
File metadata and controls
103 lines (96 loc) · 3.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
class Tracking {
http = require('http')
https = require('https')
qs = require('querystring')
apiVersion = "v3"
basePath = "https://api.trackingmore.com/"
apiKey = "Your api key"
constructor(apiKey) {
this.apiKey = apiKey
}
getReqType(url) {
return url.startsWith('https://') ? this.https : this.http
}
getReq(url, params, options = {}) {
return new Promise((resolve, reject) => {
let request = this.getReqType(url)
let keys = Object.keys(params)
url = keys.length ? (url + (url.indexOf('?') > -1 ? '&' : '?') + this.qs.stringify(params).replace(/\?$/g, '')) : url
request.get(url, options, res => {
var data = ''
res.on('data', (chunk) => {
data += chunk;
})
res.on('end', () => {
resolve(data)
})
}).on('error', err => {
reject(err)
})
})
}
postReq(url, content, method = '',options = {}) {
return new Promise((resolve, reject) => {
let request = this.getReqType(url)
options.headers = options.headers ? options.headers['content-type'] ? options.headers : {
...options.headers,
'Tracking-Api-Key': this.apiKey,
'content-type': 'application/json',
'rejectUnauthorized':false
} : {
'Tracking-Api-Key': this.apiKey,
'content-type': 'application/json',
'rejectUnauthorized':false
}
options.headers['Content-Length'] = Buffer.byteLength(content, 'utf8')
console.log(options)
let req = request.request(url, {
...options,
method: method,
}, res => {
res.setEncoding('utf8');
var data = ''
res.on('data', (chunk) => {
data += chunk
})
res.on('end', () => {
resolve(data)
})
}).on('error', err => {
reject(err)
})
req.write(content)
req.end()
})
}
async jsonp(url, params) {
let callback = '_cb'
if (params.callback) {
callback = params.callback
}
let res
const data = await this.getReq(url, {
...params,
callback
})
eval(`function ${callback}(data) {
res = data
} ` + data)
return res
}
async doRequest(path, data = '', method = '') {
const url = this.basePath+'/'+this.apiVersion+'/trackings/'+path
method = method.toUpperCase()
if (method==='GET') {
return this.getReq(url, data);
}else{
if(data===null){
data=this.qs.stringify(data);
}else{
data = JSON.stringify(data); //json format
}
return this.postReq(url, data,method);
}
}
}
module.exports = {Tracking}