-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
60 lines (50 loc) · 1.71 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
const cors = require('cors');
const next = require('next');
const Pusher = require('pusher');
const express = require('express');
const bodyParser = require('body-parser');
const dotenv = require('dotenv').config();
const Sentiment = require('sentiment');
const dev = process.env.NODE_ENV !== 'production';
const port = process.env.PORT || 3000;
const app = next({ dev });
const handler = app.getRequestHandler();
const sentiment = new Sentiment();
// Ensure that your pusher credentials are properly set in the .env file
// Using the specified variables
const pusher = new Pusher({
appId: process.env.PUSHER_APP_ID,
key: process.env.PUSHER_APP_KEY,
secret: process.env.PUSHER_APP_SECRET,
cluster: process.env.PUSHER_APP_CLUSTER,
useTLS: true,
});
app.prepare()
.then(() => {
const server = express();
const chatHistory = { messages: [] };
server.use(cors());
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: true }));
server.get('*', (req, res) => {
return handler(req, res);
});
server.post('/message', (req, res, next) => {
const { user = null, message = '', timestamp = (+new Date) } = req.body;
const sentimentScore = sentiment.analyze(message).score;
const chat = { user, message, timestamp, sentiment: sentimentScore };
chatHistory.messages.push(chat);
pusher.trigger('chat-room', 'new-message', { chat });
});
server.post('/messages', (req, res, next) => {
res.json({ ...chatHistory, status: 'success' });
});
server.listen(port, err => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
})
.catch(ex => {
console.error(ex.stack);
process.exit(1);
});