source: trip-planner-front/node_modules/needle/test/helpers.js

Last change on this file was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 1.6 KB
Line 
1var fs = require('fs');
2
3var protocols = {
4 http : require('http'),
5 https : require('https')
6}
7
8var keys = {
9 cert : fs.readFileSync(__dirname + '/keys/ssl.cert'),
10 key : fs.readFileSync(__dirname + '/keys/ssl.key')
11}
12
13var helpers = {};
14
15helpers.server = function(opts, cb) {
16
17 var defaults = {
18 code : 200,
19 headers : {'Content-Type': 'application/json'}
20 }
21
22 var mirror_response = function(req) {
23 return JSON.stringify({
24 headers: req.headers,
25 body: req.body
26 })
27 }
28
29 var get = function(what) {
30 if (!opts[what])
31 return defaults[what];
32
33 if (typeof opts[what] == 'function')
34 return opts[what](); // set them at runtime
35 else
36 return opts[what];
37 }
38
39 var finish = function(req, res) {
40 if (opts.handler) return opts.handler(req, res);
41
42 res.writeHead(get('code'), get('headers'));
43 res.end(opts.response || mirror_response(req));
44 }
45
46 var handler = function(req, res) {
47
48 req.setEncoding('utf8'); // get as string
49 req.body = '';
50 req.on('data', function(str) { req.body += str })
51 req.socket.on('error', function(e) {
52 // res.writeHead(500, {'Content-Type': 'text/plain'});
53 // res.end('Error: ' + e.message);
54 })
55
56 setTimeout(function(){
57 finish(req, res);
58 }, opts.wait || 0);
59
60 };
61
62 var protocol = opts.protocol || 'http';
63 var server;
64
65 if (protocol == 'https')
66 server = protocols[protocol].createServer(keys, handler);
67 else
68 server = protocols[protocol].createServer(handler);
69
70 server.listen(opts.port, cb);
71 return server;
72}
73
74module.exports = helpers;
Note: See TracBrowser for help on using the repository browser.