formation 5 years ago
parent
commit
776aef06bb
5 changed files with 210 additions and 0 deletions
  1. 1 0
      api/.dockerignore
  2. 41 0
      api/.gitignore
  3. 45 0
      api/api-routes.js
  4. 34 0
      api/package.json
  5. 89 0
      api/server.js

+ 1 - 0
api/.dockerignore

@@ -0,0 +1 @@
+node_modules

+ 41 - 0
api/.gitignore

@@ -0,0 +1,41 @@
+# See http://help.github.com/ignore-files/ for more about ignoring files.
+
+# compiled output
+/dist
+/tmp
+/out-tsc
+
+# dependencies
+/node_modules
+
+
+# IDEs and editors
+/.idea
+.project
+.classpath
+.c9/
+*.launch
+.settings/
+*.sublime-workspace
+
+# IDE - VSCode
+.vscode/*
+!.vscode/settings.json
+!.vscode/tasks.json
+!.vscode/launch.json
+!.vscode/extensions.json
+
+# misc
+/.sass-cache
+/connect.lock
+/coverage
+/libpeerconnection.log
+npm-debug.log
+yarn-error.log
+testem.log
+/typings
+.env
+
+# System Files
+.DS_Store
+Thumbs.db

+ 45 - 0
api/api-routes.js

@@ -0,0 +1,45 @@
+// Filename: api-routes.js
+// Initialize express router
+let router = require("express").Router();
+// Set default API response
+router.get("/", function(req, res) {
+  res.json({
+    status: "API Its Working",
+    message: "Welcome to RESTHub crafted with love!"
+  });
+});
+
+// Import user controller
+var userController = require("./controllers/users.controller");
+// user routes
+router
+  .route("/users")
+  .get(userController.index)
+  .post(userController.new);
+router
+  .route("/user/:user_id")
+  .get(userController.view)
+  .patch(userController.update)
+  .put(userController.update)
+  .delete(userController.delete);
+router.route("/user/authenticate").post(userController.authenticate);
+router
+  .route("/user/changepassword/:user_id")
+  .put(userController.changePassword);
+
+// Import Contact controller
+var contactController = require("./controllers/contact.controller");
+// Contact routes
+router
+  .route("/contacts")
+  .get(contactController.index)
+  .post(contactController.new);
+router
+  .route("/contact/:contact_id")
+  .get(contactController.view)
+  .patch(contactController.update)
+  .put(contactController.update)
+  .delete(contactController.delete);
+
+// Export API routes
+module.exports = router;

+ 34 - 0
api/package.json

@@ -0,0 +1,34 @@
+{
+    "name": "api-expressjs",
+    "version": "1.0.2",
+    "description": "Packages for expressjs apis",
+    "main": "server.js",
+    "scripts": {
+      "start": "node server.js",
+      "dev-server": "nodemon -L"
+    },
+    "dependencies": {
+      "bcryptjs": "^2.1.0",
+      "body-parser": "^1.19.0",
+      "cors": "^2.8.1",
+      "dotenv": "^8.2.0",
+      "express": "^4.17.1",
+      "express-jwt": "^6.0.0",
+      "jsonwebtoken": "^8.5.1",
+      "lodash": "^4.17.20",
+      "mongoose": "^5.10.6",
+      "q": "^1.4.1",
+      "request": "^2.88.2",
+      "rootpath": "^0.1.2"
+    },
+    "license": "MIT",
+    "devDependencies": {
+      "eslint": "^7.9.0",
+      "eslint-config-airbnb-base": "^14.2.0",
+      "eslint-config-prettier": "^6.11.0",
+      "eslint-plugin-import": "^2.22.0",
+      "eslint-plugin-prettier": "^3.1.4",
+      "nodemon": "^2.0.4",
+      "prettier": "^2.1.2"
+    }
+  }

+ 89 - 0
api/server.js

@@ -0,0 +1,89 @@
+require("dotenv").config();
+let express = require("express");
+let app = express();
+const environment = require("./config/environment");
+let cors = require("cors");
+let path = require("path");
+let bodyParser = require("body-parser");
+let expressJwt = require("express-jwt");
+// Import Mongoose
+let mongoose = require("mongoose");
+
+app.use(cors());
+app.use(bodyParser.urlencoded({ extended: true }));
+app.use(bodyParser.json());
+
+// Connect to Mongoose and set connection variable
+// MongoDB connection
+console.log("connection string", environment.mongodb.uri);
+console.log("secret", environment.secret);
+mongoose.connect(environment.mongodb.uri, {
+  useUnifiedTopology: true,
+  useNewUrlParser: true
+});
+mongoose.Promise = global.Promise;
+
+// On connection error
+mongoose.connection.on("error", (error) => {
+  console.log("Database error: ", error);
+});
+
+// On successful connection
+mongoose.connection.on("connected", () => {
+  console.log("Connected to database");
+});
+
+// addtional configuration when serving Angular SPA (static reource and Anugalr routing)
+const allowedExt = [
+  ".js",
+  ".ico",
+  ".css",
+  ".png",
+  ".jpg",
+  ".woff2",
+  ".woff",
+  ".ttf",
+  ".svg",
+  ".webmanifest"
+];
+// app.get("*", (req, res) => {
+//   if (allowedExt.filter((ext) => req.url.indexOf(ext) > 0).length > 0) {
+//     res.sendFile(path.resolve(`public/${req.url}`));
+//   } else {
+//     res.sendFile(path.resolve("public/index.html"));
+//   }
+//
+// });
+
+// Import routes
+let apiRoutes = require("./api-routes");
+
+// use JWT auth to secure the api, the token can be passed in the authorization header or querystring
+app.use(
+  expressJwt({
+    secret: environment.secret,
+    algorithms: ["HS256"],
+    getToken: function (req) {
+      if (
+        req.headers.authorization &&
+        req.headers.authorization.split(" ")[0] === "Bearer"
+      ) {
+        return req.headers.authorization.split(" ")[1];
+      } else if (req.query && req.query.token) {
+        return req.query.token;
+      }
+      return null;
+    }
+  }).unless({ path: ["/api/user/authenticate", "/api/users", "/index.html"] })
+);
+
+// Use Api routes in the App
+app.use("/api", apiRoutes);
+
+const HOST = "0.0.0.0";
+// start server
+// Launch app to listen to specified port
+const server = app.listen(process.env.EXPRESS_PORT || 3000, HOST, () => {
+  const PORT = server.address().port;
+  console.log(`Running  on http://${HOST}:${PORT}`);
+});