-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
97 lines (84 loc) · 2.2 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
97
const express = require('express');
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(express.static('public'));
const mongoose = require('mongoose');
// connect to the database
mongoose.connect('mongodb://localhost:27017/museum', {
useNewUrlParser: true
});
// Configure multer so that it will upload to '/public/images'
const multer = require('multer')
const upload = multer({
dest: './public/images/',
limits: {
fileSize: 10000000
}
});
// Create a scheme for items in the museum: a title and a path to an image.
const itemSchema = new mongoose.Schema({
title: String,
description: String,
path: String,
});
// Create a model for items in the museum.
const Item = mongoose.model('Item', itemSchema);
// Upload a photo. Uses the multer middleware for the upload and then returns
// the path where the photo is stored in the file system.
app.post('/api/photos', upload.single('photo'), async (req, res) => {
// Just a safety check
if (!req.file) {
return res.sendStatus(400);
}
res.send({
path: "/images/" + req.file.filename
});
});
app.post('/api/items', async (req, res) => {
const item = new Item({
title: req.body.title,
description: req.body.description,
path: req.body.path,
});
try {
await item.save();
res.send(item);
}
catch (error) {
console.log(error);
res.sendStatus(500);
}
});
app.get('/api/items', async (req, res) => {
try {
let items = await Item.find();
res.send(items);
} catch (error) {
console.log(error);
res.sendStatus(500);
}
});
app.delete('/api/items/:id', async (req, res) => {
let id = req.params.id;
await Item.deleteOne({_id: id});
res.send(true);
});
app.put('/api/items/:id', async (req, res) => {
try {
let new_name = req.body.title;
let new_description = req.body.description;
let id = req.params.id;
let item = await Item.findOne({_id: id});
item.title = new_name;
item.description = new_description;
await item.save();
res.send(item);
} catch (error) {
console.log(error);
}
})
app.listen(3000, () => console.log('Server listening on port 3000!'));