|
| 1 | +var restify = require('restify'); |
| 2 | +var util = require('util'); |
| 3 | +var host = process.env.HOST || 'localhost'; |
| 4 | +var port = process.env.PORT; |
| 5 | +var ENV = process.env.NODE_ENV; |
| 6 | + |
| 7 | +if (!port) { |
| 8 | + if (host === 'localhost') { |
| 9 | + port = '8080'; |
| 10 | + } else { |
| 11 | + port = '80'; |
| 12 | + } |
| 13 | +} |
| 14 | + |
| 15 | +function TestServer(args) { |
| 16 | + this.routes = args.routes; |
| 17 | + this.server = restify.createServer(); |
| 18 | + this.server.use(restify.bodyParser()); |
| 19 | + this.server.use(restify.queryParser()); |
| 20 | + main.server.router.register_routes(this.server, this.routes); |
| 21 | +} |
| 22 | + |
| 23 | +TestServer.prototype.start = function () { |
| 24 | + if (this.server) { |
| 25 | + this.server.listen(port, host); |
| 26 | + } else { |
| 27 | + throw new Error('Server not found'); |
| 28 | + } |
| 29 | +}; |
| 30 | + |
| 31 | +TestServer.prototype.stop = function () { |
| 32 | + this.server.close(); |
| 33 | +}; |
| 34 | + |
| 35 | +function HttpClient(args) { |
| 36 | + args = args || {}; |
| 37 | + if (!args.host) { |
| 38 | + throw new Error('HTTP Client requires a host param'); |
| 39 | + } |
| 40 | + |
| 41 | + this.host = args.host; |
| 42 | + this.protocol = args.protocol || 'http'; |
| 43 | + this.port = args.port; |
| 44 | + this.url = 'http://' + this.host + ':' + this.port; |
| 45 | + |
| 46 | + //this.client = restify.createStringClient({url: this.url}); |
| 47 | + this.client = restify.createJsonClient({url: this.url}); |
| 48 | +} |
| 49 | + |
| 50 | +HttpClient.prototype.get = function (path_or_options, cb) { |
| 51 | + this.client.get(path_or_options, function (err, req, res, data) { |
| 52 | + cb(err, data, res, req); |
| 53 | + }); |
| 54 | +}; |
| 55 | + |
| 56 | +HttpClient.prototype.post = function (path_or_options, body, cb) { |
| 57 | + this.client.post(path_or_options, body, function (err, req, res, data) { |
| 58 | + cb(err, data, res, req); |
| 59 | + }); |
| 60 | +}; |
| 61 | + |
| 62 | +HttpClient.prototype.put = function (path_or_options, body, cb) { |
| 63 | + this.client.put(path_or_options, body, function (err, req, res, data) { |
| 64 | + cb(err, data, res, req); |
| 65 | + }); |
| 66 | +}; |
| 67 | + |
| 68 | +HttpClient.prototype.del = function (path_or_options, cb) { |
| 69 | + this.client.del(path_or_options, function (err, req, res, data) { |
| 70 | + cb(err, data, res, req); |
| 71 | + }); |
| 72 | +}; |
| 73 | + |
| 74 | +var http = { |
| 75 | + client: function () { |
| 76 | + return new HttpClient({host: host, port: port}); |
| 77 | + }, |
| 78 | + |
| 79 | + server: { |
| 80 | + create: function (routes) { |
| 81 | + return new TestServer({routes: routes}); |
| 82 | + } |
| 83 | + }, |
| 84 | + |
| 85 | + host: host, |
| 86 | + port: port |
| 87 | +}; |
| 88 | + |
| 89 | +module.exports = http; |
| 90 | + |
0 commit comments