/
notificationRegistrationGateway.js
58 lines (50 loc) · 2.13 KB
/
notificationRegistrationGateway.js
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
// This is an implementation of the Revealing Module Pattern
// ref: http://addyosmani.com/resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript
//
// ---- Example of how to call ----
// ---- You only need to call init if you want to overide the default options ----
// var options = { client: someClient, requestHandler: someHandler, eventNotificationUrl: 'someUrl' };
// gateway.init( options );
// gateway.register( registrationData, voiceMailType, function ( err, success) { ... });
//
module.exports = (function() {
var client;
var requestHandler = require( '../libs/requestHandler' );
var eventNotificationUrl = 'http://localhost:3000/events';
function init ( options ) {
client = options.client || client;
requestHandler = options.requestHandler || requestHandler;
eventNotificationUrl = options.eventNotificationUrl || eventNotificationUrl;
}
function createRequest ( registration, notificationType ) {
var url = require( 'url' ).parse( notificationType.registrationUrl );
var http = (url.protocol == 'http') ? require( 'http' ) : require( 'https' );
client = client || http.createClient( url.port, url.hostname );
var requestOptions = {
'Host': url.hostname,
'Accept': 'application/json',
'Content-Type': 'application/json'
};
var message = {
'registrationKey': registration.key,
'eventNotificationUrl': eventNotificationUrl,
'notificationType': notificationType.name
};
var request = client.request( 'GET', url.path, requestOptions );
request.write( JSON.stringify( message ) );
return request;
}
function register ( registration, notificationType, callBack ) {
requestHandler.handle( createRequest( registration, notificationType ), function( err, response ) {
if ( response.statusCode >= 200 && response.statusCode < 300 ) {
callBack( null, true );
} else {
callBack( new Error( 'Error registering notification at:' + notificationType.registrationUrl + '. StatusCode ' + response.statusCode + ': ' + response.body ), false );
}
} );
}
return {
init: init,
register: register
};
}());