Skip to content

Commit b332a59

Browse files
author
Rohan Jain
committed
Add a alert to BrowserStack utility
1 parent b6a5d1a commit b332a59

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

lib/utils.js

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
var config = require('./config');
2+
var http = require('http');
3+
var url = require('url');
4+
var querystring = require('querystring');
25

36
var titleCase = function toTitleCase(str) {
47
return str.replace(/\w\S*/g, function (txt) {
@@ -27,7 +30,66 @@ var objectSize = function objectSize (obj) {
2730
return size;
2831
};
2932

33+
var alertBrowserStack = function alertBrowserStack (subject, content, params, fn) {
34+
var endpoint = config.alert_endpoint || "http://www.browserstack.com/automate/alert";
35+
var urlObject = url.parse(endpoint);
36+
37+
if (typeof params !== 'object') {
38+
params = {};
39+
}
40+
41+
if (typeof fn !== 'function') {
42+
fn = function() {};
43+
}
44+
45+
params.subject = subject;
46+
params.content = content;
47+
48+
var options = {
49+
hostname: urlObject.hostname,
50+
port: urlObject.port,
51+
path: urlObject.path,
52+
method: 'POST',
53+
auth: config.username + ":" + config.key
54+
};
55+
56+
var callback = function (res) {
57+
var response = "";
58+
res.setEncoding( "utf8" );
59+
res.on( "data", function( chunk ) {
60+
response += chunk;
61+
});
62+
res.on( "end", function() {
63+
if ( res.statusCode !== 200 ) {
64+
var message;
65+
if ( res.headers[ "content-type" ].indexOf( "json" ) !== -1 ) {
66+
var resp = JSON.parse( response );
67+
message = resp.message;
68+
message += ' - ' + resp.errors.map(function(err){
69+
return '`' + err.field + '`' + ' ' + err.code
70+
}).join(', ')
71+
} else {
72+
message = response;
73+
}
74+
if ( !message && res.statusCode === 403 ) {
75+
message = "Forbidden";
76+
}
77+
fn( new Error( message ) );
78+
} else {
79+
fn( null, JSON.parse( response ) );
80+
}
81+
});
82+
};
83+
84+
var request = http.request(options, callback);
85+
request.write(querystring.stringify(params));
86+
request.end();
87+
88+
return request;
89+
}
90+
3091
exports.titleCase = titleCase;
3192
exports.uuid = uuid;
3293
exports.browserString = browserString;
3394
exports.objectSize = objectSize;
95+
exports.alertBrowserStack = alertBrowserStack;

0 commit comments

Comments
 (0)