/
helpers.js
182 lines (161 loc) · 5.63 KB
/
helpers.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
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
/*
* Helpers for various tasks
*
*/
// Dependencies
var config = require('./config');
var crypto = require('crypto');
var https = require('https');
var querystring = require('querystring');
var path = require('path');
var fs = require('fs');
// Container for all the helpers
var helpers = {};
// Parse a JSON string to an object in all cases, without throwing
helpers.parseJsonToObject = function(str){
try{
var obj = JSON.parse(str);
return obj;
} catch(e){
return {};
}
};
// Create a SHA256 hash
helpers.hash = function(str){
if(typeof(str) == 'string' && str.length > 0){
var hash = crypto.createHmac('sha256', config.hashingSecret).update(str).digest('hex');
return hash;
} else {
return false;
}
};
// Create a string of random alphanumeric characters, of a given length
helpers.createRandomString = function(strLength){
strLength = typeof(strLength) == 'number' && strLength > 0 ? strLength : false;
if(strLength){
// Define all the possible characters that could go into a string
var possibleCharacters = 'abcdefghijklmnopqrstuvwxyz0123456789';
// Start the final string
var str = '';
for(i = 1; i <= strLength; i++) {
// Get a random charactert from the possibleCharacters string
var randomCharacter = possibleCharacters.charAt(Math.floor(Math.random() * possibleCharacters.length));
// Append this character to the string
str+=randomCharacter;
}
// Return the final string
return str;
} else {
return false;
}
};
helpers.sendTwilioSms = function(phone,msg,callback){
// Validate parameters
phone = typeof(phone) == 'string' && phone.trim().length == 10 ? phone.trim() : false;
msg = typeof(msg) == 'string' && msg.trim().length > 0 && msg.trim().length <= 1600 ? msg.trim() : false;
if(phone && msg){
// Configure the request payload
var payload = {
'From' : config.twilio.fromPhone,
'To' : '+1'+phone,
'Body' : msg
};
var stringPayload = querystring.stringify(payload);
// Configure the request details
var requestDetails = {
'protocol' : 'https:',
'hostname' : 'api.twilio.com',
'method' : 'POST',
'path' : '/2010-04-01/Accounts/'+config.twilio.accountSid+'/Messages.json',
'auth' : config.twilio.accountSid+':'+config.twilio.authToken,
'headers' : {
'Content-Type' : 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(stringPayload)
}
};
// Instantiate the request object
var req = https.request(requestDetails,function(res){
// Grab the status of the sent request
var status = res.statusCode;
// Callback successfully if the request went through
if(status == 200 || status == 201){
callback(false);
} else {
callback('Status code returned was '+status);
}
});
// Bind to the error event so it doesn't get thrown
req.on('error',function(e){
callback(e);
});
// Add the payload
req.write(stringPayload);
// End the request
req.end();
} else {
callback('Given parameters were missing or invalid');
}
};
// Get the string content of a template, and use provided data for string interpolation
helpers.getTemplate = function(templateName,data,callback){
templateName = typeof(templateName) == 'string' && templateName.length > 0 ? templateName : false;
data = typeof(data) == 'object' && data !== null ? data : {};
if(templateName){
var templatesDir = path.join(__dirname,'/../templates/');
fs.readFile(templatesDir+templateName+'.html', 'utf8', function(err,str){
if(!err && str && str.length > 0){
// Do interpolation on the string
var finalString = helpers.interpolate(str,data);
callback(false,finalString);
} else {
callback('No template could be found');
}
});
} else {
callback('A valid template name was not specified');
}
};
// Add the universal header and footer to a string, and pass provided data object to header and footer for interpolation
helpers.addUniversalTemplates = function(str,data,callback){
str = typeof(str) == 'string' && str.length > 0 ? str : '';
data = typeof(data) == 'object' && data !== null ? data : {};
// Get the header
helpers.getTemplate('_header',data,function(err,headerString){
if(!err && headerString){
// Get the footer
helpers.getTemplate('_footer',data,function(err,footerString){
if(!err && headerString){
// Add them all together
var fullString = headerString+str+footerString;
callback(false,fullString);
} else {
callback('Could not find the footer template');
}
});
} else {
callback('Could not find the header template');
}
});
};
// Take a given string and data object, and find/replace all the keys within it
helpers.interpolate = function(str,data){
str = typeof(str) == 'string' && str.length > 0 ? str : '';
data = typeof(data) == 'object' && data !== null ? data : {};
// Add the templateGlobals to the data object, prepending their key name with "global."
for(var keyName in config.templateGlobals){
if(config.templateGlobals.hasOwnProperty(keyName)){
data['global.'+keyName] = config.templateGlobals[keyName]
}
}
// For each key in the data object, insert its value into the string at the corresponding placeholder
for(var key in data){
if(data.hasOwnProperty(key) && typeof(data[key] == 'string')){
var replace = data[key];
var find = '{'+key+'}';
str = str.replace(find,replace);
}
}
return str;
};
// Export the module
module.exports = helpers;