-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
96 lines (85 loc) · 1.9 KB
/
server.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
'use strict'
// declaring express, body parser, PORT
const express = require('express');
const app = express();
const router = express.Router();
const bodyParser = require('body-parser');
// const port = process.env.PORT || 3000;
// body parser for use on response
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// public views
app.use(express.static(__dirname + '/public'));
// HTML Endpoint
app.get('/', function home(req,res){
res.sendFile(__dirname + '/index.html');
});
// DB Route
let db = require('./models');
// GET ALL
app.get('/cars', (req,res)=>{
db.Car.find()
.exec((err,cars)=>{
if(err){
console.log("Get error: ",err);
}
res.json(cars);
});
});
// SHOW
app.get('/cars/:id', (req,res)=>{
db.Car.findOne({_id: req.params.id}, (err, data)=>{
if(err){
console.log("Show errror: ",err);
}
res.json(data);
});
});
// POST
app.post('/cars', (req,res)=>{
let newCar = new db.Car({
year: req.body.year,
make: req.body.make,
model: req.body.model,
picture: req.body.picture
});
newCar.save((err,car)=>{
if(err){
console.log("Save Error: ",err);
}
res.json(car);
});
});
// DELETE
app.delete('/cars/:id', (req,res)=>{
db.Car.remove({_id: req.params.id}, (err,deletedCar)=>{
if(err){
console.log("Delete Error: ", err);
}
res.json("yoooo");
});
});
// PUT
app.put('/cars/:id', (req,res)=>{
db.Car.findOne({_id: req.params.id}, (err, foundCar)=>{
if (err){
console.log("Update Error: ", err);
}
foundCar.id = req.params.id;
foundCar.year = req.body.year;
foundCar.make = req.body.make;
foundCar.model = req.body.model;
foundCar.picture = req.body.picture;
foundCar.save((err, car)=>{
if (err){
console.log("Update Save Error: ", err);
}
console.log('Updated ', car.model);
res.json(car);
});
});
});
// Server
app.listen(process.env.PORT || 3000, ()=>{
console.log("Server Running on PORT:3000");
});