ソースを参照

Load db on application load and expose it in app variable

Tati 7 年 前
コミット
981580bf25

+ 2 - 0
ktchn/package.json

@@ -14,6 +14,7 @@
     "@types/cookie-parser": "^1.4.1",
     "@types/express": "^4.16.0",
     "@types/jest": "^23.3.12",
+    "@types/mongodb": "^3.1.19",
     "@types/natural": "^0.2.33",
     "@types/request": "^2.48.0",
     "@types/request-promise": "^4.1.42",
@@ -23,6 +24,7 @@
     "debug": "~2.6.9",
     "dotenv": "^6.2.0",
     "express": "~4.16.0",
+    "mongodb": "^3.1.13",
     "morgan": "~1.9.0",
     "nano": "^7.1.0",
     "natural": "^0.6.3",

+ 9 - 0
ktchn/src/config.ts

@@ -0,0 +1,9 @@
+module.exports = {
+	name: 'API',
+	env: process.env.NODE_ENV || 'development',
+	port: process.env.PORT || 3000,
+	base_url: process.env.BASE_URL || 'http://localhost:3000',
+	db: {
+		uri: process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017/api',
+	},
+};

+ 0 - 5
ktchn/src/couchdb.ts

@@ -1,5 +0,0 @@
-import nano from 'nano';
-
-const couchdb = nano(process.env.COUCHDB_URL || 'http://localhost:5984/');
-
-export default couchdb;

+ 0 - 5
ktchn/src/recipes/controller.ts

@@ -1,5 +0,0 @@
-import { Recipe } from './model';
-import { create } from './data';
-import { DocumentInsertResponse } from 'nano';
-
-export const saveRecipe = (data: Recipe): Promise<DocumentInsertResponse> => create(data);

+ 0 - 16
ktchn/src/recipes/data/index.ts

@@ -1,16 +0,0 @@
-import CouchDb from "../../couchdb";
-import { Recipe } from "../model";
-import { MaybeIdentifiedDocument, ViewDocument, MaybeDocument, DocumentInsertResponse } from "nano";
-
-const Recipes = CouchDb.use('recipes');
-
-type CouchDBTypes = 'recipe';
-
-function identifyDocument<T>(document: T, type: CouchDBTypes):MaybeDocument {
-  return {
-    ...document,
-    couchdb_type: type,
-  } as MaybeDocument;
-}
-
-export const create = (recipe: Recipe): Promise<DocumentInsertResponse> => Recipes.insert(identifyDocument(recipe, 'recipe'));

+ 0 - 0
ktchn/src/recipes/data/schema.ts


+ 5 - 11
ktchn/src/recipes/routes.ts

@@ -1,7 +1,6 @@
 import { Request, Response, Router } from "express";
 import Scrape from "./scrape";
-import { saveRecipe } from "./controller";
-import nano = require("nano");
+import { Recipe } from './model';
 
 class RecipeRoutes {
   public router: Router;
@@ -17,15 +16,10 @@ class RecipeRoutes {
       });
     })
     this.router.post("/", (req, res, next) => {
-      return saveRecipe(req.body).then((x)=>{
-        res.json(x)
-      }).catch((error: any) => { // TODO: Reserch on CouchDB responses types
-        res.status(error.headers.statusCode).send(
-          {
-            name: error.error,
-            message: error.message,
-          }
-        )
+      const recipe = req.body as Recipe;
+      console.log(req.app.locals.db);
+      res.json({
+        message: 'k'
       });
     })
     this.router.post("/scrape", (req, res, next) => {

+ 30 - 27
ktchn/src/server.ts

@@ -7,55 +7,58 @@ import rootRouter from "./routes/root";
 import recipeRouter from "./recipes/routes";
 import nano from 'nano';
 import dotenv from 'dotenv';
+import MongoClient from 'mongodb';
 
 class App {
-  public express: express.Application;
-  //public db: nano.DatabaseScope;
+  public app: express.Application;
 
   constructor() {
     this.dotENV();
-    this.express = express();
+    this.app = express();
     this.middleware();
     this.routes();
     this.launchConf();
-    //this.db = this.couchDB();
   }
 
   private dotENV(): void {
     dotenv.config();
   }
-
-  private couchDB(): nano.DatabaseScope {
-    return nano(process.env.COUCHDB_URL || 'http://localhost:5984/').db;
-  }
   
   private routes(): void {
-    this.express.use("/recipes", recipeRouter);
-    this.express.use("/", rootRouter);
+    this.app.use("/recipes", recipeRouter);
+    this.app.use("/", rootRouter);
   }
 
   private middleware(): void {
-    this.express.set("port", process.env.PORT || 3000);
-    this.express.use(logger("dev"));
-    this.express.use(express.json());
-    this.express.use(bodyParser.json());
-    this.express.use(bodyParser.urlencoded({ extended: false }));
-    this.express.use(cookieParser());
-    this.express.use(express.static(path.join(__dirname, "public")));
+    this.app.set("port", process.env.PORT || 3000);
+    this.app.use(logger("dev"));
+    this.app.use(express.json());
+    this.app.use(bodyParser.json());
+    this.app.use(bodyParser.urlencoded({ extended: false }));
+    this.app.use(cookieParser());
+    this.app.use(express.static(path.join(__dirname, "public")));
+  }
+
+  private launchMongoDb(): Promise<MongoClient.MongoClient> {
+    return MongoClient.connect('mongodb://127.0.0.1:27017/api');
   }
 
   private launchConf() {
-    const port = this.express.get("port");
-    console.log('port', port);
-    this.express.listen(port, () => {
-      console.log(
-        ("App is runnnning at http://localhost:%d in %s mode"),
-        port,
-        this.express.get("env")
-      );
-      console.log("Press CTRL-C to stop");
+    this.launchMongoDb().then(dbClient => {
+      this.app.locals.db = dbClient;
+      const port = this.app.get("port");
+      this.app.listen(port, () => {
+        console.log(
+          ("App is runnnning at http://localhost:%d in %s mode"),
+          port,
+          this.app.get("env")
+        );
+        console.log("Press CTRL-C to stop");
+      });
+    }).catch(error => {
+      console.log(`Error loading database: ${error}`)
     });
   }
 }
 
-export default new App().express;
+export default new App().app;