server.ts 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. import * as path from "path";
  2. import cookieParser from "cookie-parser";
  3. import * as bodyParser from "body-parser";
  4. import logger from "morgan";
  5. import express from "express";
  6. import rootRouter from "./routes/root";
  7. import recipeRouter from "./recipes/routes";
  8. import ingredientsRouter from './ingredients/routes';
  9. import plannerRouter from './planner/routes';
  10. import shoppingRouter from './shopping/routes';
  11. import dotenv from 'dotenv';
  12. import MongoClient from 'mongodb';
  13. import { RecipeDB } from './recipes/model';
  14. namespace Application {
  15. locals: {
  16. db: MongoClient.MongoClient
  17. }
  18. }
  19. declare global {
  20. namespace Express {
  21. interface Response {
  22. app: Application,
  23. locals: {
  24. savedData: RecipeDB
  25. }
  26. }
  27. }
  28. }
  29. class App {
  30. public app: express.Application;
  31. constructor() {
  32. this.dotENV();
  33. this.app = express();
  34. this.middleware();
  35. this.launchApp();
  36. }
  37. private dotENV(): void {
  38. dotenv.config();
  39. }
  40. private routes(db: MongoClient.Db): void {
  41. this.app.use("/recipes", new recipeRouter(db).router);
  42. this.app.use("/ingredients", new ingredientsRouter(db).router);
  43. this.app.use('/planner', new plannerRouter(db).router);
  44. this.app.use('/shopping', new shoppingRouter(db).router);
  45. this.app.use("/", rootRouter);
  46. }
  47. private middleware(): void {
  48. this.app.set("port", process.env.PORT || 3000);
  49. this.app.use(logger("dev"));
  50. this.app.use(express.json());
  51. this.app.use(bodyParser.json({limit: '10mb'}));
  52. this.app.use(bodyParser.urlencoded({ limit: '10mb', extended: true }));
  53. this.app.use(cookieParser());
  54. this.app.use(express.static(path.join(__dirname, "public")));
  55. this.app.use((req, res, next)=> {
  56. res.header("Access-Control-Allow-Origin", "*");
  57. res.header('Access-Control-Allow-Methods', 'DELETE, PUT');
  58. res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  59. if ('OPTIONS' == req.method) {
  60. res.sendStatus(200);
  61. } else {
  62. next();
  63. }
  64. })
  65. }
  66. private connectDB(): Promise<MongoClient.Db> {
  67. return MongoClient.connect('mongodb://127.0.0.1:27017').then(dbClient => dbClient.db('ktchn'));
  68. }
  69. private startDB(db: MongoClient.Db): void {
  70. db.createCollection('ingredients').then(collection => {
  71. collection.createIndex({
  72. name: 'text',
  73. variants: 'text'
  74. }, {
  75. //@ts-ignore
  76. weights: {
  77. name: 10,
  78. variants: 5
  79. }
  80. })
  81. });
  82. db.createCollection('recipes');
  83. db.createCollection('planner');
  84. db.createCollection('shopping').then(collection => {
  85. collection.findOne({}).then(shoppingCart => {
  86. if (!shoppingCart) {
  87. collection.insertOne({
  88. date: new Date(),
  89. items: []
  90. })
  91. }
  92. })
  93. });
  94. }
  95. private launchApp() {
  96. this.connectDB().then(db => {
  97. this.routes(db);
  98. this.startDB(db);
  99. const port = this.app.get("port");
  100. this.app.listen(port, '0.0.0.0', () => {
  101. console.log(
  102. ("App is runnnning at http://localhost:%d in %s mode"),
  103. port,
  104. this.app.get("env")
  105. );
  106. console.log("Press CTRL-C to stop");
  107. });
  108. }).catch(error => {
  109. console.log(`Error loading database: ${error}`)
  110. });
  111. }
  112. }
  113. export default new App().app;