-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
113 lines (101 loc) · 2.43 KB
/
index.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
//libs
const express = require('express');
const app = express();
const bodyParser = require('body-parser')
const assert = require('assert');
//response headers
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
//public folder for resources
app.use(express.static('public'))
app.use(express.json());
app.use( bodyParser.json() );
app.get('/api', (req, res) => {
res.json({
message: "Got Hi."
});
});
app.post('/api', (req, res) => {
res.json({
message: "Posted Hi."
});
});
app.put('/api', (req, res) => {
res.json({
message: "Put Hi."
});
});
app.delete('/api', (req, res) => {
res.json({
message: "Deleted Hi."
});
});
app.get('/api/chat', (req, res) => {
chatCollection.find({}).toArray(function(err, items) {
res.json({
chats:items
});
});
});
app.post('/api/chat', (req, res) => {
console.log(req.body.name+" says "+req.body.message);
var messageObject = {
"name":req.body.name,
"message":req.body.message,
"date": new Date()
}
chatCollection.insertOne(messageObject);
res.json({
message: req.body.name+" says "+req.body.message
});
});
app.put('/api/chat', (req, res) => {
res.json({
message: "Put chat."
});
});
app.delete('/api/chat', (req, res) => {
var my_id = req.body._id;
var chatToDelete = req.body;
delete chatToDelete._id
console.log("Deleting: "+chatToDelete.message);
chatCollection.findOneAndDelete({_id:ObjectId(my_id)}, function(err, obj) {
if (err) throw err;
res.json({
message: "Deleted "+chatToDelete._id
});
});
});
/*
//if you don't need mongo, you can just open a server directly
app.listen(8080, function() {
console.log('Listening on port 8080...')
});
*/
//mongo
var MongoClient = require('mongodb').MongoClient;
var connectionString = 'mongodb://localhost:27017/chatDB';
var ObjectId = require('mongodb').ObjectId;
var db;
var chatDB;
var chatCollection;
// Connect to Mongo on start
MongoClient.connect(connectionString, function(err, mdb) {
assert.equal(null, err);
if (err) {
console.log('Unable to connect to Mongo.')
process.exit(1)
} else {
//switch to your db.
chatDB = mdb.db("chatDB");
chatCollection = chatDB.collection("chatCollection");
//listen on a port
app.listen(80, function() {
console.log('Listening on port 80...')
})
}
})