Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merging in develop for heroku #24

Merged
merged 17 commits into from Dec 21, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 3 additions & 4 deletions .gitignore
Expand Up @@ -56,7 +56,6 @@ typings/

# dotenv environment variables file
.env

.travis.yml

package-lock.json
Procfile
package-lock.json
.jshintrc
13 changes: 6 additions & 7 deletions README.md
@@ -1,8 +1,8 @@
# MyRecipes, server
# Recipe Studio, server

## API endpoints

API URL: [`api.myrecipes.pw/v1`](http://api.myrecipes.pw/v1)
API URL: [`https://api.recipe.studio`](https://api.recipe.studio)

### Creating records
POST to `/recipe/new` in the following schema model:
Expand All @@ -11,14 +11,13 @@ POST to `/recipe/new` in the following schema model:
name : String
ingredients : [
{
name : String
ingredient : String
ingredient : String (ingredient ID)
quantity : Number
measure : String
units : String
}, {more ingredients....}
]
picture : String
author : String
image : String
author : String (user ID)
}
```

Expand Down
51 changes: 32 additions & 19 deletions app.js
@@ -1,30 +1,43 @@
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var users = require('./routes/users');
var recipes = require('./routes/recipes');
var ingredients = require('./routes/ingredients');
var express = require("express");
var path = require("path");
var logger = require("morgan");
var cookieParser = require("cookie-parser");
var bodyParser = require("body-parser");

var index = require("./routes/index");
var users = require("./routes/users");
var recipes = require("./routes/recipes");
var ingredients = require("./routes/ingredients");
var search = require("./routes/search");

var app = express();

app.use(logger('dev'));
app.use(logger("dev"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/user', users);
app.use('/recipe', recipes);
app.use('/ingredient', ingredients);
app.use(express.static(path.join(__dirname, "public")));

let allowCrossDomain = function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
res.header(
"Access-Control-Allow-Headers",
"Content-Type, Authorization, Content-Length, X-Requested-With"
);
next();
};
app.use(allowCrossDomain);

app.use("/", index);
app.use("/user", users);
app.use("/recipe", recipes);
app.use("/ingredient", ingredients);
app.use("/search", search);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
var err = new Error("Not Found");
err.status = 404;
next(err);
});
Expand All @@ -33,7 +46,7 @@ app.use(function(req, res, next) {
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
res.locals.error = req.app.get("env") === "development" ? err : {};

// send code
res.status(err.status || 500);
Expand Down
34 changes: 15 additions & 19 deletions bin/www
Expand Up @@ -4,16 +4,16 @@
* Module dependencies.
*/

var app = require('../app');
var debug = require('debug')('recipe-studio-api:server');
var http = require('http');
var app = require("../app");
var debug = require("debug")("recipe-studio-api:server");
var http = require("http");

/**
* Get port from environment and store in Express.
*/

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
var port = normalizePort(process.env.PORT || "3000");
app.set("port", port);

/**
* Create HTTP server.
Expand All @@ -26,8 +26,8 @@ var server = http.createServer(app);
*/

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
server.on("error", onError);
server.on("listening", onListening);

/**
* Normalize a port into a number, string, or false.
Expand All @@ -54,22 +54,20 @@ function normalizePort(val) {
*/

function onError(error) {
if (error.syscall !== 'listen') {
if (error.syscall !== "listen") {
throw error;
}

var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
var bind = typeof port === "string" ? "Pipe " + port : "Port " + port;

// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
case "EACCES":
console.error(bind + " requires elevated privileges");
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
case "EADDRINUSE":
console.error(bind + " is already in use");
process.exit(1);
break;
default:
Expand All @@ -83,8 +81,6 @@ function onError(error) {

function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
console.info('Listening on ' + bind);
var bind = typeof addr === "string" ? "pipe " + addr : "port " + addr.port;
console.info("Listening on " + bind);
}
5 changes: 4 additions & 1 deletion package.json
Expand Up @@ -10,6 +10,9 @@
"cookie-parser": "~1.4.3",
"debug": "~2.6.9",
"express": "~4.15.5",
"morgan": "~1.9.0"
"firebase-admin": "^5.5.1",
"mongodb": "^3.0.0-rc0",
"morgan": "~1.9.0",
"node-fetch": "^1.7.3"
}
}
6 changes: 3 additions & 3 deletions routes/index.js
@@ -1,9 +1,9 @@
var express = require('express');
var express = require("express");
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
res.status(200).json({ 'message': 'API is up and running!' });
router.get("/", function(req, res, next) {
res.status(200).json({ message: "API is up and running!" });
});

module.exports = router;
138 changes: 125 additions & 13 deletions routes/ingredients.js
@@ -1,21 +1,133 @@
var express = require('express');
var express = require("express");
var router = express.Router();
var assert = require("assert");

var MongoClient = require("mongodb").MongoClient;
var db_conn_str = process.env.DB_CONN_STR;
if (!db_conn_str) {
console.error("DB_CONN_STR variable not set!");
} else {
console.log("Connection string: ", db_conn_str);
}

/* GET ingredients listing. */
router.get('/', (req, res) => {
res.status(200).json({'ingredients': []});
router.get("/", (req, res) => {
res
.status(400)
.json({ message: "Invalid request: no ingredient ID specified" });
});

// GET all ingredients
router.get("/all", mongoGetAll);

// GET ingredient by :id
router.get('/:id', (req, res) => {
res.status(200).json(
{
'ingredient': {
'id': (req.params.id),
'name': 'ingredientName'
}
}
);
});
router.get("/:id", mongoGet);

// POST create new ingredient
router.post("/new", mongoPost);

// DATABASE FUNCTIONS

// DB create function
function mongoPost(req, res, next) {
let d = new Date();
console.log("creating at ", d);

let newItem = {
name: req.body.name,
created: d,
category: req.body.category
};

// connect to DB here
try {
MongoClient.connect(db_conn_str, (err, db) => {
assert.equal(null, err, "Could not connect to db");

// insert into db
db
.db("recipe-studio")
.collection("ingredients")
.insertOne(newItem, (err, result) => {
assert.equal(null, err);
assert.equal(1, result.insertedCount);

// send response data
res.status(201).json(newItem);
});

db.close();
});
} catch (err) {
console.error(err);
res.status(500).json({ message: "Error creating ingredient", error: err });
}
}

// DB read one function
function mongoGet(req, res, next) {
let mongodb = require("mongodb");

// check for correct ID length
let iid = req.params.id;
if (iid.length != 24) {
res.status(400).json({ message: "Invalid ingredient ID" });
return;
}

// connect to db
try {
MongoClient.connect(db_conn_str, (err, db) => {
assert.equal(null, err, "Could not connect to db");

db
.db("recipe-studio")
.collection("ingredients")
.findOne({ _id: new mongodb.ObjectID(iid) }, (err, ingredient) => {
if (!ingredient) {
res
.status(404)
.json({ message: "Ingredient " + iid + " not found" });
} else {
// send response data
res.status(200).json(ingredient);
}
});

db.close();
});
} catch (err) {
console.error(err);
res.status(500).json({ message: "Error fetching ingredient", error: err });
}
}

// DB read all function
function mongoGetAll(req, res, next) {
// connect to db
try {
MongoClient.connect(db_conn_str, (err, db) => {
assert.equal(null, err, "Could not connect to db");

db
.db("recipe-studio")
.collection("ingredients")
.find({})
.toArray((err, ingredients) => {
// send response data
if (err) {
res.status(500).json({ message: "Error getting data", error: err });
} else {
res.status(200).json(ingredients);
}
});

db.close();
});
} catch (err) {
console.error(err);
res.status(500).json({ message: "Error fetching ingredients", error: err });
}
}

module.exports = router;