forked from scottgonzalez/node-browserstack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbrowserstack.js
More file actions
103 lines (90 loc) · 2.09 KB
/
browserstack.js
File metadata and controls
103 lines (90 loc) · 2.09 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
var http = require( "http" ),
querystring = require( "querystring" );
function extend( a, b ) {
for ( var p in b ) {
a[ p ] = b[ p ];
}
return a;
};
function Client( settings) {
if ( !settings.username ) {
throw new Error( "Username is required." );
}
if ( !settings.password ) {
throw new Error( "Password is required." );
}
this._username = settings.username;
this._password = settings.password;
this._authHeader = "Basic " +
new Buffer( this._username + ":" + this._password ).toString( "base64" );
}
extend( Client.prototype, {
getBrowsers: function( fn ) {
this.request({
path: this.path( "/browsers" )
}, fn );
},
createWorker: function( options, fn ) {
var data = querystring.stringify( options );
this.request({
path: this.path( "/worker" ),
method: "POST"
}, data, fn );
},
terminateWorker: function( id, fn ) {
this.request({
path: this.path( "/worker/" + id ),
method: "DELETE"
}, fn );
},
path: function( path ) {
return "/1" + path;
},
request: function( options, data, fn ) {
if ( typeof data === "function" ) {
fn = data;
data = null;
}
var headers = {
authorization: this._authHeader
};
headers[ "content-length" ] = typeof data === "string" ? data.length : 0;
var req = http.request( extend({
host: "api.browserstack.com",
port: 80,
method: "GET",
headers: headers
}, options ), function( res ) {
var response = "";
res.setEncoding( "utf8" );
res.on( "data", function( chunk ) {
response += chunk;
});
res.on( "end", function() {
if ( res.statusCode !== 200 ) {
var message;
if ( res.headers[ "content-type" ].indexOf( "json" ) !== -1 ) {
message = JSON.parse( response ).message;
} else {
message = response;
}
if ( !message && res.statusCode === 403 ) {
message = "Forbidden";
}
fn( new Error( message ) );
} else {
fn( null, JSON.parse( response ) );
}
});
});
if ( data ) {
req.write( data );
}
req.end();
}
});
module.exports = {
createClient: function( settings ) {
return new Client( settings );
}
};