Skip to content

Commit

Permalink
Prettier
Browse files Browse the repository at this point in the history
  • Loading branch information
tsongas committed Jun 23, 2018
1 parent d25719e commit 02e508c
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 72 deletions.
10 changes: 6 additions & 4 deletions config.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
'use strict';
exports.DATABASE_URL = process.env.DATABASE_URL || 'mongodb://localhost/restaurants-app';
exports.TEST_DATABASE_URL = process.env.TEST_DATABASE_URL || 'mongodb://localhost/test-restaurants-app';
exports.PORT = process.env.PORT || 8080;
"use strict";
exports.DATABASE_URL =
process.env.DATABASE_URL || "mongodb://localhost/restaurants-app";
exports.TEST_DATABASE_URL =
process.env.TEST_DATABASE_URL || "mongodb://localhost/test-restaurants-app";
exports.PORT = process.env.PORT || 8080;
36 changes: 20 additions & 16 deletions models.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
'use strict';
"use strict";

const mongoose = require('mongoose');
const mongoose = require("mongoose");

// this is our schema to represent a restaurant
const restaurantSchema = mongoose.Schema({
name: {type: String, required: true},
borough: {type: String, required: true},
cuisine: {type: String, required: true},
name: { type: String, required: true },
borough: { type: String, required: true },
cuisine: { type: String, required: true },
address: {
building: String,
// coord will be an array of string values
Expand All @@ -15,33 +15,37 @@ const restaurantSchema = mongoose.Schema({
zipcode: String
},
// grades will be an array of objects
grades: [{
date: Date,
grade: String,
score: Number
}]
grades: [
{
date: Date,
grade: String,
score: Number
}
]
});

// *virtuals* (http://mongoosejs.com/docs/guide.html#virtuals)
// allow us to define properties on our object that manipulate
// properties that are stored in the database. Here we use it
// to generate a human readable string based on the address object
// we're storing in Mongo.
restaurantSchema.virtual('addressString').get(function() {
restaurantSchema.virtual("addressString").get(function() {
return `${this.address.building} ${this.address.street}`.trim();
});

// this virtual grabs the most recent grade for a restaurant.
restaurantSchema.virtual('grade').get(function() {
const gradeObj = this.grades.sort((a, b) => {return b.date - a.date;})[0] || {};
restaurantSchema.virtual("grade").get(function() {
const gradeObj =
this.grades.sort((a, b) => {
return b.date - a.date;
})[0] || {};
return gradeObj.grade;
});

// this is an *instance method* which will be available on all instances
// of the model. This method will be used to return an object that only
// exposes *some* of the fields we want from the underlying data
restaurantSchema.methods.serialize = function() {

return {
id: this._id,
name: this.name,
Expand All @@ -54,6 +58,6 @@ restaurantSchema.methods.serialize = function() {

// note that all instance methods and virtual properties on our
// schema must be defined *before* we make the call to `.model`.
const Restaurant = mongoose.model('Restaurant', restaurantSchema);
const Restaurant = mongoose.model("Restaurant", restaurantSchema);

module.exports = {Restaurant};
module.exports = { Restaurant };
100 changes: 48 additions & 52 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,55 +1,51 @@
'use strict';
"use strict";

const express = require('express');
const mongoose = require('mongoose');
const express = require("express");
const mongoose = require("mongoose");

// Mongoose internally uses a promise-like object,
// but its better to make Mongoose use built in es6 promises
mongoose.Promise = global.Promise;

// config.js is where we control constants for entire
// app like PORT and DATABASE_URL
const { PORT, DATABASE_URL } = require('./config');
const { Restaurant } = require('./models');
const { PORT, DATABASE_URL } = require("./config");
const { Restaurant } = require("./models");

const app = express();
app.use(express.json());

// GET requests to /restaurants => return 10 restaurants
app.get('/restaurants', (req, res) => {
Restaurant
.find()
app.get("/restaurants", (req, res) => {
Restaurant.find()
// we're limiting because restaurants db has > 25,000
// documents, and that's too much to process/return
.then(restaurants => {
res.json({
restaurants: restaurants.map(
(restaurant) => restaurant.serialize())
restaurants: restaurants.map(restaurant => restaurant.serialize())
});
})
.catch(err => {
console.error(err);
res.status(500).json({ message: 'Internal server error' });
res.status(500).json({ message: "Internal server error" });
});
});

// can also request by ID
app.get('/restaurants/:id', (req, res) => {
app.get("/restaurants/:id", (req, res) => {
Restaurant
// this is a convenience method Mongoose provides for searching
// by the object _id property
.findById(req.params.id)
.then(restaurant => res.json(restaurant.serialize()))
.catch(err => {
console.error(err);
res.status(500).json({ message: 'Internal server error' });
res.status(500).json({ message: "Internal server error" });
});
});


app.post('/restaurants', (req, res) => {

const requiredFields = ['name', 'borough', 'cuisine'];
app.post("/restaurants", (req, res) => {
const requiredFields = ["name", "borough", "cuisine"];
for (let i = 0; i < requiredFields.length; i++) {
const field = requiredFields[i];
if (!(field in req.body)) {
Expand All @@ -59,28 +55,26 @@ app.post('/restaurants', (req, res) => {
}
}

Restaurant
.create({
name: req.body.name,
borough: req.body.borough,
cuisine: req.body.cuisine,
grades: req.body.grades,
address: req.body.address
})
Restaurant.create({
name: req.body.name,
borough: req.body.borough,
cuisine: req.body.cuisine,
grades: req.body.grades,
address: req.body.address
})
.then(restaurant => res.status(201).json(restaurant.serialize()))
.catch(err => {
console.error(err);
res.status(500).json({ message: 'Internal server error' });
res.status(500).json({ message: "Internal server error" });
});
});


app.put('/restaurants/:id', (req, res) => {
app.put("/restaurants/:id", (req, res) => {
// ensure that the id in the request path and the one in request body match
if (!(req.params.id && req.body.id && req.params.id === req.body.id)) {
const message = (
const message =
`Request path id (${req.params.id}) and request body id ` +
`(${req.body.id}) must match`);
`(${req.body.id}) must match`;
console.error(message);
return res.status(400).json({ message: message });
}
Expand All @@ -89,7 +83,7 @@ app.put('/restaurants/:id', (req, res) => {
// if the user sent over any of the updatableFields, we udpate those values
// in document
const toUpdate = {};
const updateableFields = ['name', 'borough', 'cuisine', 'address'];
const updateableFields = ["name", "borough", "cuisine", "address"];

updateableFields.forEach(field => {
if (field in req.body) {
Expand All @@ -101,19 +95,18 @@ app.put('/restaurants/:id', (req, res) => {
// all key/value pairs in toUpdate will be updated -- that's what `$set` does
.findByIdAndUpdate(req.params.id, { $set: toUpdate })
.then(restaurant => res.status(204).end())
.catch(err => res.status(500).json({ message: 'Internal server error' }));
.catch(err => res.status(500).json({ message: "Internal server error" }));
});

app.delete('/restaurants/:id', (req, res) => {
Restaurant
.findByIdAndRemove(req.params.id)
app.delete("/restaurants/:id", (req, res) => {
Restaurant.findByIdAndRemove(req.params.id)
.then(restaurant => res.status(204).end())
.catch(err => res.status(500).json({ message: 'Internal server error' }));
.catch(err => res.status(500).json({ message: "Internal server error" }));
});

// catch-all endpoint if client makes request to non-existent endpoint
app.use('*', function (req, res) {
res.status(404).json({ message: 'Not Found' });
app.use("*", function(req, res) {
res.status(404).json({ message: "Not Found" });
});

// closeServer needs access to a server object, but that only
Expand All @@ -123,21 +116,24 @@ let server;

// this function connects to our database, then starts the server
function runServer(databaseUrl, port = PORT) {

return new Promise((resolve, reject) => {
mongoose.connect(databaseUrl, err => {
if (err) {
return reject(err);
mongoose.connect(
databaseUrl,
err => {
if (err) {
return reject(err);
}
server = app
.listen(port, () => {
console.log(`Your app is listening on port ${port}`);
resolve();
})
.on("error", err => {
mongoose.disconnect();
reject(err);
});
}
server = app.listen(port, () => {
console.log(`Your app is listening on port ${port}`);
resolve();
})
.on('error', err => {
mongoose.disconnect();
reject(err);
});
});
);
});
}

Expand All @@ -146,7 +142,7 @@ function runServer(databaseUrl, port = PORT) {
function closeServer() {
return mongoose.disconnect().then(() => {
return new Promise((resolve, reject) => {
console.log('Closing server');
console.log("Closing server");
server.close(err => {
if (err) {
return reject(err);
Expand Down

0 comments on commit 02e508c

Please sign in to comment.