Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions api/model/book.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
var mongoose = require("mongoose");
var Schema = mongoose.Schema;

var schema = new Schema({
title: { type: String },
published: { type: Number },
authors: [
{
name: String,
dob: String
}
]
});

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice Work

module.exports = mongoose.model("Books", schema);
53 changes: 53 additions & 0 deletions api/routes/books.authors.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// Include :seriesId
const router = require("express").Router({ mergeParams: true });
Copy link

@MadEste MadEste Jul 21, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

const Books = require("../model/book");

router.get("/", async (req, res, next) => {
const status = 200;

const { authors } = await Books.findById(req.params.bookId).select("authors");
res.json({ status, authors });
});

router.get("/:id", async (req, res, next) => {
const status = 200;

const books = await Books.findById(req.params.bookId);

const author = books.authors.id(req.params.id);

res.status(status).json({ status, author });
});

router.post("/", async (req, res, next) => {
const status = 201;
const books = await Books.findById(req.params.bookId);

books.authors.push(req.body);
await books.save();

const author = books.authors[books.authors.length - 1];
res.status(status).json({ status, author });
});

router.put("/:id", async (req, res, next) => {
const status = 200;
const books = await Books.findById(req.params.bookId);

const author = books.authors.id(req.params.id);
Object.assign(author, req.body);
await books.save();

res.status(status).json({ status, author });
});

router.delete("/:id", async (req, res, next) => {
const status = 200;
const books = await Books.findById(req.params.bookId);
const author = books.authors.id(req.params.id).remove();
await books.save();

res.status(status).json({ status, author });
});

module.exports = router;
103 changes: 55 additions & 48 deletions api/routes/books.js
Original file line number Diff line number Diff line change
@@ -1,73 +1,80 @@
const router = require('express').Router()
const { generate: generateId } = require('shortid')
const router = require("express").Router();
const { generate: generateId } = require("shortid");
const Books = require("../model/book");

const books = [
{
id: 'j9U3iNIQi',
title: 'The Colour of Magic',
id: "j9U3iNIQi",
title: "The Colour of Magic",
published: 1983,
authors: [
{
name: 'Sir Terry Pratchett',
dob: '04-28-1948'
name: "Sir Terry Pratchett",
dob: "04-28-1948"
}
]
},
{
id: 'ubQnXOfJV',
title: 'Stardust',
id: "ubQnXOfJV",
title: "Stardust",
published: 1997,
authors: [
{
name: 'Neil Gaiman',
dob: '11-10-1960'
name: "Neil Gaiman",
dob: "11-10-1960"
}
]
}
];

router.get('/', (req, res, next) => {
const status = 200
const response = books

res.json({ status, response })
})
router.get("/", async (req, res, next) => {
const status = 200;

router.post('/', (req, res, next) => {
const status = 201

books.push({ id: generateId(), ...req.body })
const response = books

res.json({ status, response })
})
Books.find().then(response => {
res.json({ status, response });
});
});
/************************************************* */
router.post("/", async (req, res, next) => {
const status = 201;

router.get('/:id', (req, res, next) => {
const status = 200
const response = books.find(({ id }) => id === req.params.id)
try {
Books.create(req.body).then(response => {
res.json({ status, response });
});
} catch (error) {
console.error(error);
const e = new Error("Sonthing went wrong");

res.json({ status, response })
})

router.put('/:id', (req, res, next) => {
const status = 200
const response = { id: req.params.id, ...req.body }
const single = books.find(({ id }) => id === req.params.id)
const index = books.indexOf(single)

books.splice(index, 1, response)

res.json({ status, response })
})
e.status = 400;
next(e);
}
});
/************************************************* */
router.get("/:id", async (req, res, next) => {
const status = 200;

router.delete('/:id', (req, res, next) => {
const status = 200
const response = books.find(({ id }) => id === req.params.id)
const index = books.indexOf(response)
Books.findById(req.params.id).then(response => {
res.json({ status, response });
});
});
/************************************************* */
router.put("/:id", async (req, res, next) => {
const status = 200;
const response = await Books.findOneAndUpdate(
{ _id: req.params.id },
{ title: req.body.title, published: req.body.published },
{ new: true }
);

books.splice(index, 1)
res.json({ status, response });
});
/************************************************* */
router.delete("/:id", async (req, res, next) => {
const status = 200;
const response = await Books.findOneAndDelete({ _id: req.params.id });

res.json({ status, response })
})
res.json({ status, response });
});

module.exports = router
module.exports = router;
44 changes: 24 additions & 20 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,37 +1,41 @@
const { MONGO_DB_CONNECTION, NODE_ENV, PORT } = process.env
const express = require('express')
const mongoose = require('mongoose')
const app = express()
const { MONGO_DB_CONNECTION, NODE_ENV, PORT } = process.env;
const express = require("express");
const mongoose = require("mongoose");
const app = express();

// Database Connection
if (MONGO_DB_CONNECTION) {
mongoose.connect(MONGO_DB_CONNECTION, { useNewUrlParser: true })
console.log('Connected to database...')
mongoose.connect(MONGO_DB_CONNECTION, {
useNewUrlParser: true,
useFindAndModify: false
});
console.log("Connected to database...");
} else {
console.log('Could not connect to database!')
console.log("Could not connect to database!");
}

// Application-level Middleware
if (NODE_ENV === 'development') app.use(require('morgan')('dev'))
app.use(require('body-parser').json())
if (NODE_ENV === "development") app.use(require("morgan")("dev"));
app.use(require("body-parser").json());

// Routes
app.use('/api/books', require('./api/routes/books'))
app.use("/api/books", require("./api/routes/books"));
app.use("/api/books/:bookId/authors", require("./api/routes/books.authors"));

// Not Found Handler
app.use((req, res, next) => {
const error = new Error(`Could not ${req.method} ${req.path}`)
error.status = 404
next(error)
})
const error = new Error(`Could not ${req.method} ${req.path}`);
error.status = 404;
next(error);
});

// Error Handler
app.use((err, req, res, next) => {
if (NODE_ENV === 'development') console.error(err)
const { message, status } = err
res.status(status).json({ status, message })
})
if (NODE_ENV === "development") console.error(err);
const { message, status } = err;
res.status(status).json({ status, message });
});

// Open Connection
const listener = () => console.log(`Listening on Port ${PORT}!`)
app.listen(PORT, listener)
const listener = () => console.log(`Listening on Port ${PORT}!`);
app.listen(PORT, listener);
Loading