server.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. var fs = require('fs');
  2. var request = require('request');
  3. var connect = require('connect');
  4. var serveStatic = require('serve-static');
  5. var bodyParser = require('body-parser');
  6. var config = require('./config.json');
  7. var apiEndpoint = 'https://api.cloudflare.com/client/v4';
  8. var isProd = config.isProd === undefined || config.isProd;
  9. var port = config.port || 8000;
  10. var app = connect();
  11. var serve = serveStatic('.', {'index': []});
  12. var serveIndex = function(req, res, next) {
  13. if(isProd) {
  14. req.url = '/index.html';
  15. serve(req, res, next);
  16. }
  17. else {
  18. var html = fs.readFileSync('./index.html', {encoding: 'utf8'});
  19. res.setHeader('Content-Type', 'text/html; charset=utf8');
  20. res.end(html.replace('/assets/bundle.js', 'http://localhost:8001/assets/bundle.js'));
  21. }
  22. };
  23. app.use(bodyParser.json());
  24. app.use(function(req, res, next) {
  25. if(req.url.startsWith('/api')) {
  26. var headers = {
  27. 'Authorization': `Bearer ${config.token}`
  28. }
  29. var path = req.url.substring(4);
  30. if(path === '/zones') {
  31. var params = {uri: apiEndpoint+path, headers: headers, json: true};
  32. request.get(params).pipe(res);
  33. }
  34. else if(path.startsWith('/zones')) {
  35. request({
  36. method: req.method,
  37. uri: apiEndpoint+path,
  38. headers: headers,
  39. qs: req.method == 'GET' ? {per_page: 999} : {},
  40. body: req.body,
  41. json: true
  42. }).pipe(res);
  43. }
  44. // deny other request paths for now
  45. else {
  46. next();
  47. }
  48. }
  49. else {
  50. next();
  51. }
  52. });
  53. app.use(serve);
  54. app.use(serveIndex);
  55. if(!isProd) {
  56. var WebpackDevServer = require('webpack-dev-server');
  57. var HotModuleReplacementPlugin = require('webpack/lib/HotModuleReplacementPlugin');
  58. var webpack = require('webpack');
  59. var webpackConfig = require('./webpack.config.js');
  60. webpackConfig.entry = [
  61. "webpack-dev-server/client?http://localhost:8001",
  62. "webpack/hot/dev-server",
  63. webpackConfig.entry
  64. ];
  65. webpackConfig.output.path = '/';
  66. webpackConfig.output.publicPath = 'http://localhost:8001/assets/';
  67. webpackConfig.plugins = webpackConfig.plugins || [];
  68. webpackConfig.plugins.push(new HotModuleReplacementPlugin());
  69. webpackConfig.devtool = 'eval';
  70. var devServer = new WebpackDevServer(webpack(webpackConfig), {
  71. contentBase: 'http://localhost:8000',
  72. publicPath: webpackConfig.output.publicPath,
  73. hot: true
  74. })
  75. devServer.listen(8001);
  76. }
  77. app.listen(port);