-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
194 lines (177 loc) · 6.19 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
//requirements
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
// const mongoose = require('mongoose');
const MongoClient=require('mongodb').MongoClient
var methodOverride = require('method-override')
const url = 'mongodb://127.0.0.1:27017'
const dbName='xmeme'
const connectionString='mongodb+srv://user123:[email protected]/xmeme?retryWrites=true&w=majority'
//setting db and collection
let db
let memesCollection
// MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => {
// if (err) return console.log(err)
// // Storing a reference to the database so you can use it later
// db = client.db(dbName)
// memesCollection = db.collection('meme')
// console.log(`Connected MongoDB: ${url}`)
// console.log(`Database: ${dbName}`)
// })
function getNextSequence(db, name, callback) {
db.collection("counters").findAndModify( { _id: name }, null, { $inc: { seq: 1 } }, function(err, result){
if(err) callback(err, result);
callback(err, result.value.seq);
} );
}
//function to check if json object is empty
function isEmpty(obj) {
return Object.keys(obj).length === 0;
}
MongoClient.connect(connectionString, { useUnifiedTopology: true })
.then(client => {
console.log('Connected to Database')
const db = client.db('xmeme')
memesCollection = db.collection('meme')
app.use(methodOverride('_method'))
//for taking url values in
app.use(bodyParser.urlencoded({extended: true}))
//for json type
app.use(bodyParser.json())
// app.get('/',(req,res)=>{
// res.send("Hello World")
// })
//set correct path folders for views and express
app.set('view engine', 'ejs')
app.use(express.static('public'))
//paths
app.get('/',(req,res)=>{
var msg=""
memesCollection.find().toArray()
.then(results => {
res.render('index.ejs', {memes:results,msg:msg})
})
.catch(err => {
res.status(500).send({
message: err.message || "Some error occurred while retrieving memes."
})
})
})
app.get('/memes',(req,res)=>{
memesCollection.find().toArray()
.then(results => {
res.json(results)
})
.catch(error=>console.error(error))
})
app.get('/memes/:memeId',(req,res)=>{
memesCollection.find({ _id: parseInt(req.params.memeId)}).toArray()
.then(results => {
// res.send(typeof results)
// res.json(results)
if(isEmpty(results)){
res.sendStatus(404)
}else{
res.json(results)
}
})
.catch(error=>console.error(error))
})
app.post('/memes', (req,res)=>{
// getNextSequence(db, "userid", function(err, result){
// if(!err){
// db.collection('meme').insert({
// "_id": result,
// "name" : req.body.name,
// "url" : req.body.url,
// "caption" : req.body.caption
// }).then(result=>{
// // console.log(req.body.name)
// res.redirect('/')
// })
// .catch(error=>console.error(error))
// }
// })
// memesCollection.insertOne(req.body)
// .then(result=>{
// console.log(req.body.name)
// res.redirect('/')
// })
// .catch(error=>console.error(error))
memesCollection.find({ "name" : req.body.name, "url" : req.body.url, "caption" : req.body.caption }).toArray()
// memesCollection.find({ "name" : req.body.name}).toArray()
.then(docs => {
if(isEmpty(docs)){
getNextSequence(db, "userid", function(err, result){
if(!err){
db.collection('meme').insert({
"_id": result,
"name" : req.body.name,
"url" : req.body.url,
"caption" : req.body.caption
}).then(result=>{
// console.log(req.body.name)
res.redirect('/')
})
.catch(error=>console.error(error))
}
})
}else{
var msg="The meme already exists"
memesCollection.find().toArray()
.then(results => {
res.status(409).render('index.ejs', {memes:results, msg:msg})
})
.catch(err => {
res.status(500).send({
message: err.message || "Some error occurred while retrieving memes."
})
})
}
})
.catch(error=>console.error(error))
})
app.patch('/memes/:memeId', (req, res) => {
memesCollection.findOneAndUpdate(
{ _id: parseInt(req.params.memeId)},
{
$set: {
"url": req.body.url,
"caption": req.body.caption
}
},
{
upsert: true
}
)
.then(result =>{
// res.json('Success')
res.status(200).redirect('/')
})
.catch(error => res.status(400).redirect('/'))
})
// app.delete('/quotes', (req, res) => {
// memesCollection.deleteOne(
// { name: req.body.name }
// )
// .then(result => {
// if (result.deletedCount === 0) {
// return res.json('No quote to delete')
// }
// res.json(`Deleted Darth Vadar's quote`)
// })
// .catch(error => console.error(error))
// })
// ========================
// Listen
// ========================
const isProduction = process.env.NODE_ENV === 'production'
const port = process.env.PORT || 3000;
app.listen(port, function () {
console.log(`listening on ${port}`)
})
console.log("XMEME HERE IN CONSOLE")
})
.catch(console.error)
//function to make mongodb id autoincrement and start from 1