-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
180 lines (155 loc) · 4.45 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
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
import express from 'express';
import { MongoClient, ObjectId } from 'mongodb';
import dotenv from 'dotenv';
import cors from 'cors';
import dayjs from 'dayjs';
import joi from 'joi';
const app = express();
app.use(express.json());
app.use(cors());
dotenv.config();
const mongoClient = new MongoClient(process.env.MONGO_URI);
let db;
mongoClient.connect(() => {
db = mongoClient.db('bate_papo_uol');
});
let activeUser = '';
let activeParticipants = '';
const nameSchema = joi.string().required();
const messageSchema = joi.object({
to: joi.string().required(),
text: joi.string().required(),
type: joi
.string()
.required()
.valid(...['message', 'private_message']),
from: joi.valid(activeParticipants),
});
app.post('/participants', async (req, res) => {
try {
const name = req.body.name;
const participantName = await db
.collection('participants')
.find({ name: name })
.toArray();
const validation = nameSchema.validate(name, { abortEarly: true });
if (validation.error) {
res.sendStatus(422);
} else if (participantName.length > 0) {
res.sendStatus(409);
} else {
const participant = await db.collection('participants').insertOne({
name: name,
lastStatus: Date.now(),
});
const message = await db.collection('messages').insertOne({
from: name,
to: 'Todos',
text: 'entra na sala...',
type: 'status',
time: dayjs(Date.now()).format('HH:mm:ss'),
});
activeUser = name;
res.sendStatus(201);
}
} catch (err) {
res.sendStatus(err);
}
});
app.get('/participants', async (req, res) => {
try {
const participants = await db.collection('participants').find().toArray();
activeParticipants = participants;
res.send(participants);
} catch (err) {
res.sendStatus(err);
}
});
app.post('/messages', async (req, res) => {
try {
const message = req.body;
const to = req.body.to;
const text = req.body.text;
const type = req.body.type;
const from = req.headers.user;
const time = dayjs(Date.now()).format('HH:mm:ss');
const validation = messageSchema.validate(message, {
abortEarly: true,
});
if (validation.error) {
res.sendStatus(422);
} else {
const messages = await db.collection('messages').insertOne({
to: to,
text: text,
type: type,
from: from,
time: time,
});
res.sendStatus(201);
}
} catch (err) {
res.sendStatus(err);
}
});
app.get('/messages', async (req, res) => {
try {
const messages = await db.collection('messages').find().toArray();
const filteredMessages = messages.filter(
(message) =>
message.to === 'Todos' ||
message.to === activeUser ||
message.from === activeUser
);
if (!req.query.limit) {
res.send(filteredMessages);
return;
} else {
const limit = req.query.limit;
res.send([...filteredMessages].reverse().slice(0, limit).reverse());
}
} catch (err) {
res.sendStatus(err);
}
});
app.post('/status', async (req, res) => {
const participant = await db
.collection('participants')
.find({ name: req.headers.user })
.toArray();
if(participant.length < 1) {
res.sendStatus(404)
} else {
await db.collection('participants').updateOne({name: participant.name}, {$set: {lastStatus: Date.now()}})
res.sendStatus(200);
}
});
setInterval(async () => {
const timeLimit = Date.now() - 10000
const inactiveParticipants = await db.collection('participants').find({lastStatus: {$lt: timeLimit}}).toArray()
await db.collection('participants').deleteMany({lastStatus: {$lt: timeLimit}})
inactiveParticipants.map(async inactiveParticipant => {
await db.collection('messages').insertOne({
from: inactiveParticipant.name,
to: 'Todos',
text: 'sai da sala...',
type: 'status',
time: dayjs(Date.now()).format('HH:mm:ss')
})
})
}, 15000)
app.delete('/messages/:message_id', async (req, res) => {
const user = req.headers.user;
const id = req.params.message_id
const message = await db.collection('messages').find({_id: {$eq: new ObjectId(id)}}).toArray();
if(!message) {
res.sendStatus(404);
} else if (message[0].from !== user) {
res.sendStatus(401)
} else {
await db.collection('messages').deleteOne({_id: {$eq: new ObjectId(id)}})
}
});
app.listen(5000, () => {
console.log('Listening on port 5000');
});