-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
93 lines (76 loc) · 2.34 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
import express from 'express';
import 'dotenv/config';
import { getGoogleAuthURL, getGoogleUser } from './config/google-auth.js';
import { User } from './models/User.model.js';
import mongoose from 'mongoose';
import './config/mongoose.js';
import { getAttachments } from './utils/get-attachments.js';
const app = express();
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.get('/', (req, res) => {
res.render('pages/index');
});
app.get('/auth/google', (req, res) => {
res.redirect(getGoogleAuthURL());
});
app.get('/auth/callback', async(req, res) => {
try {
const googleUser = await getGoogleUser(req.query);
const { id, email, name } = googleUser.data;
let user = await User.findOne({email});
if (!user) {
user = new User({
_id: new mongoose.Types.ObjectId(),
googleId: id,
name,
email,
refresh_token: googleUser.refresh_token
});
await user.save();
}
res.redirect(`/messages/search/${user._id}`);
} catch(err) {
res.status(500).json({ error: err.message });
}
});
app.get('/messages/search/:userId', async(req, res) => {
try {
const attachments = await getAttachments(req.params.userId, '');
if(!attachments) {
return res.render('pages/search-messages', { data: {
errorMsg: 'No Results found'
}
})
}
const attachmentNames = attachments.map((data) => data.originalFileName);
return res.render('pages/search-messages', { data: {
attachmentNames
}});
} catch(err) {
res.status(500).json({ error: err.message });
}
});
app.post('/messages/search/:userId', async(req, res) => {
try {
const searchQuery = req.body.searchQuery;
const attachments = await getAttachments(req.params.userId, searchQuery);
if(!attachments) {
return res.render('pages/search-messages', { data: {
errorMsg: 'No Results found',
searchQuery
}
})
}
const attachmentNames = attachments.map((data) => data.originalFileName);
return res.render('pages/search-messages', { data: {
attachmentNames,
searchQuery
}});
} catch(err) {
res.status(500).json({ error: err.message });
}
})
app.listen(3000, () => console.log('Server running on port 3000'));