Advertisement
Guest User

Untitled

a guest
Mar 29th, 2019
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.05 KB | None | 0 0
  1. import Promise from 'bluebird';
  2. import server from 'express';
  3. import cookie from 'cookie';
  4. import cookieParser from 'cookie-parser';
  5. import bodyParser from 'body-parser';
  6. import morgan from 'morgan';
  7. import helmet from 'helmet';
  8. import cors from 'cors';
  9. import userAgent from 'express-useragent';
  10. import mongoose from 'mongoose';
  11. import redis from 'redis';
  12.  
  13. import config from './config';
  14. import Routes from './src/routes'; // импортируем все пути нашего API
  15. import { checkClientParams } from './src/middlewares'; // промежуточная валидация клиента, будет разобрана более подробно
  16.  
  17. const app = server();
  18.  
  19. try {
  20. const isProduction = (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'development');
  21.  
  22. const port = process.env.NODE_ENV === 'production' ? config.prodPort : config.devPort;
  23.  
  24. const mongoUserLogin = config.mongo.mongoUserLogin;
  25. const mongoUserPassword = config.mongo.mongoUserPassword;
  26. const mongoConnectionString = config.mongo.mongoConnectionString;
  27.  
  28. const mongooseOptions = {
  29. auth: {
  30. user: mongoUserLogin,
  31. password: mongoUserPassword,
  32. },
  33. useNewUrlParser: true,
  34. reconnectTries: 10,
  35. reconnectInterval: 500,
  36. };
  37.  
  38. app.use(cookieParser());
  39. app.use(helmet());
  40. app.use(cors());
  41. app.use(helmet.noCache());
  42. app.use(bodyParser.urlencoded({ extended: false }));
  43. app.use(bodyParser.json());
  44. app.use(morgan(isProduction ? 'tiny' : 'dev'));
  45. app.use(userAgent.express());
  46.  
  47. const redisClient = redis.createClient(); // создаем подключение к redis
  48.  
  49. app.use(checkClientParams); // при каждом запросе проверяем параметры клиента
  50. app.use((req, res, next) => {
  51. res.header("Content-Type", "application/json; charset=utf-8");
  52. res.header("Access-Control-Allow-Origin", config.originHost);
  53. res.header("Access-Control-Allow-Credentials", "true");
  54. res.header("Access-Control-Allow-Headers",
  55. "Origin, X-Requested-With, Content-Type," +
  56. "user-agent, Accept, accept-encoding, " +
  57. "accept-language, cookie, cache-control, " +
  58. "if-none-match, if-modified-since, x-proxy-api-host, " +
  59. "x-forwarded-for, x-access-token, x-session-token"
  60. );
  61. next();
  62. });
  63. app.use(function(req, res, next) {
  64. req.redisClient = redisClient; // вместо импортирования в модули объявляем в контекст express redis-клиент
  65. next();
  66. });
  67.  
  68. redisClient.on("error", function (err) {
  69. console.log("Error " + err);
  70. });
  71.  
  72. Routes(app);
  73.  
  74. mongoose.connect(mongoConnectionString, mongooseOptions)
  75. .then(
  76. () => {
  77. console.log('Mongo is connected');
  78. app.listen(port, (err) => {
  79. if(!err) {
  80. console.log(`Run server on ${port} port`);
  81. }
  82. });
  83. },
  84. )
  85. .catch(
  86. (error) => {
  87. console.log(error); // тут обрабатываем ошибки подключения к базе
  88. }
  89. );
  90. } catch (error) {
  91. console.log(error);
  92. }
  93. module.exports = app;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement