-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathroutes.js
81 lines (70 loc) · 2.23 KB
/
routes.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
const express = require('express');
const router = express.Router();
const records = require('./records');
function asyncHandler(cb){
return async (req,res, next) => {
try {
await cb(req, res, next);
} catch(err) {
next(err);
}
}
}
// Send a GET request to /quotes to READ a list of quotes
router.get('/quotes', async (req, res)=>{
const quotes = await records.getQuotes();
res.json(quotes);
});
// Send a GET request to /quotes/:id to READ(view) a quote
router.get('/quotes/:id', async (req, res)=>{
try {
const quote = await records.getQuote(req.params.id);
if(quote){
res.json(quote);
} else {
res.status(404).json({message: "Quote not found."});
}
} catch(err) {
res.status(500).json({message: err.message});
}
});
// Send a GET request to /quotes/quote/random to READ (view) a random quote
router.get('/quotes/quote/random', asyncHandler(async(req,res,next) =>{
const quote = await records.getRandomQuote();
res.json(quote);
}));
router.post('/quotes', asyncHandler( async (req, res)=>{
if(req.body.author && req.body.quote){
const quote = await records.createQuote({
quote: req.body.quote,
author: req.body.author
});
res.status(201).json(quote);
} else {
res.status(400).json({message: "Quote and author required."});
}
}));
// Send a PUT request to /quotes/:id to UPDATE (edit) a quote
router.put('/quotes/:id', asyncHandler(async(req,res) => {
const quote = await records.getQuote(req.params.id);
if(quote){
quote.quote = req.body.quote;
quote.author = req.body.author;
await records.updateQuote(quote);
res.status(204).end();
} else {
res.status(404).json({message: "Quote Not Found"});
}
}));
// Send a DELETE request to /quotes/:id DELETE a quote
router.delete("/quotes/:id", async(req,res, next) => {
try {
throw new Error("Something terrible happened!");
const quote = await records.getQuote(req.params.id);
await records.deleteQuote(quote);
res.status(204).end();
} catch(err){
next(err);
}
});
module.exports = router;