-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
80 lines (70 loc) · 2.62 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
const Datastore = require('nedb');
const express = require('express');
const app = express();
const database = new Datastore('memes.db');
database.loadDatabase();
app.use(express.static('public'));
app.use(express.json());
app.get('/memes', async (req, res) => {
console.log('Memes were fetched...');
database.find({}, (err, data) => {
res.send(data);
});
// res.send('spps');
});
app.get('/memes/:id', async (req, res) => {
console.log('Memes were fetched...');
database.find({ date: parseInt(req.params.id) }, (err, data) => {
console.log(data);
if (data.length === 0)
res.status(404).send('404 not found!');
else
res.send(data);
});
// res.send('spps');
});
app.post('/memes', (req, res) => {
console.log('trying to perform post');
// console.log(req.body);
if (isValidMeme(req.body)) {
database.find({ name: req.body.name }, (err, data) => {
console.log(data);
if (data.length != 0)
res.status(409).send({ state: "Author name already exists.." });
else
database.find({ url: req.body.url }, (err, data) => {
console.log(data);
if (data.length != 0)
res.status(409).send({ state: "Image URL already exists.." });
else
database.find({ caption: req.body.caption }, (err, data) => {
console.log(data);
if (data.length != 0)
res.status(409).send({ state: "Caption already exists.." });
else {
const id = Date.now();
const meme = {
name: req.body.name,
url: req.body.url,
caption: req.body.caption,
date: id
};
console.log('insert ho rha hai....');
database.insert(meme);
console.log(meme);
res.send(JSON.stringify({ id: id }));
}
});
});
});
}
else
console.log({ state: 'Invalid Data' });
});
function isValidMeme(req) {
if (!req.name || !req.url || !req.caption)
return false;
return true;
}
const port = process.env.PORT || 9999;
app.listen(port, () => console.log(`Listening on port ${port}...`));