-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
107 lines (97 loc) · 2.64 KB
/
app.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
const express = require('express');
const exphbs = require('express-handlebars');
const path = require('path');
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
const redis = require('redis');
const dummyData = require('./helpers/dummy_data');
const allUsers = dummyData.allUsers;
const allRepositories = dummyData.allRepositories;
function getRepositoryByID(id) {
let ret = null;
allRepositories.forEach((repository) => {
if (repository.id == id) {
ret = repository;
}
});
return ret;
}
function getUserByID(id) {
let ret = null;
allUsers.forEach((user) => {
if (user.feedId == id) {
ret = user;
}
});
return ret;
}
let client = redis.createClient();
try {
client.on('connect', function () {
console.log('Connected to Redis...');
console.log('Cleaning all users keys...');
allUsers.forEach((user) => {
client.del(user.feedId);
});
console.log('Clean Complete');
});
} catch (error) {
console.log('Failed to connect Redis');
}
const port = 3000;
const app = express();
app.engine('handlebars', exphbs({ defaultLayout: 'main' }));
app.set('view engine', 'handlebars');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(methodOverride('_method'));
app.get('/', function (req, res, next) {
res.render('feed', {
users: allUsers
});
});
app.get('/repositories', function (req, res, next) {
res.render('repositories', {
repositories: allRepositories
});
});
app.post('/user/feed', function (req, res, next) {
let id = req.body.id;
const user = getUserByID(id);
client.zrevrange(id, 0, -1, (error, data) => {
if (error) {
console.log(error);
}
if (!data || data.length == 0) {
res.render('feed', {
error: `Feed of ${user} is empty!`,
users: allUsers
});
} else {
res.render('feed', {
user: user,
feed: data,
users: allUsers
});
}
});
});
app.post('/repositories', function (req, res, next) {
const repositoryId = req.body.repositoryId;
const action = req.body.action;
const repository = getRepositoryByID(repositoryId);
const stringDate = new Date().toString();
const newFeed = `${action} on ${repository.name} [${stringDate}]`;
const interestedUsers = repository.getInterestedUsers();
interestedUsers.forEach((interested) => {
client.zadd(interested.feedId, interested.feedSize + 1, newFeed);
interested.feedSize++;
});
res.render('repositories', {
message: newFeed,
repositories: allRepositories
});
});
app.listen(port, function () {
console.log('Server started on port ' + port);
});