-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.ts
181 lines (157 loc) · 4.36 KB
/
server.ts
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
181
import 'dotenv/config';
import express, { Request, Response } from 'express';
import cors from 'cors';
import { createServer } from 'http';
import { Server, Socket } from 'socket.io';
import next from 'next';
import passport from 'passport';
import session from 'express-session';
import strategy, { findUser, isAuthenticated } from './services/auth';
import { User } from '@prisma/client';
// Prisma
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
export { prisma };
// Redis
import { createClient } from 'redis';
import connectRedis from 'connect-redis';
const redisClient = createClient({
url: process.env.REDIS_URL || 'redis://localhost:6379',
legacyMode: true
});
redisClient.connect().catch(error => {
console.log('Error connecting to Redis:', error);
});
const RedisStore = connectRedis(session);
// Routes
import usersRoute from './routes/userRouter';
import groupsRoute from './routes/groupRouter';
import messageRoute from './routes/messageRouter';
const port = parseInt(process.env.PORT || '3000', 10);
const dev = process.env.NODE_ENV !== 'production';
const nextServer = next({ dev });
const handle = nextServer.getRequestHandler();
class SocketUser {
userID: string;
socketID: string;
groupID: string | undefined;
constructor(userID: string, socketID: string) {
this.userID = userID;
this.socketID = socketID;
}
setGroupID(groupID: string) {
this.groupID = groupID;
}
}
nextServer.prepare().then(() => {
const app = express();
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(
session({
// @ts-ignore
store: new RedisStore({ client: redisClient }),
secret: process.env.SESSION_SECRET!,
resave: false,
saveUninitialized: false,
cookie: { maxAge: 1000 * 60 * 60 * 24 * 1, sameSite: 'lax' }
})
);
// Passport
passport.use(strategy);
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser((user: any, done) => {
if (user['password']) {
delete user['password'];
}
done(null, user);
});
passport.deserializeUser((user: User, done) => {
findUser(user.email)
.then(user => {
if (user && user['password']) {
user.password = '';
}
done(null, user);
})
.catch(error => {
done(error);
});
});
app.get('/', isAuthenticated, (req: Request, res: Response) => {
return handle(req, res);
});
app.use('/api/users', usersRoute);
app.use('/api/groups', groupsRoute);
app.use('/api/messages', messageRoute);
app.use((error: any, req: any, res: any, next: any) => {
console.log('Error occured:', error);
res.json({
message: error.message || 'An unknown error occured.',
error: true
});
});
app.all('*', (req: Request, res: Response) => {
return handle(req, res);
});
const httpServer = createServer(app);
// Socket.io
const io = new Server(httpServer, {
cors: {
origin: '*',
methods: ['GET', 'POST']
}
});
let users: SocketUser[] = [];
io.on('connection', (socket: Socket) => {
// When creating a new user
socket.on('newUser', (userID: string) => {
if (!userID) return;
const user = users.find(user => user.userID === userID);
if (user) {
user.socketID = socket.id;
return;
}
const newUser = new SocketUser(userID, socket.id);
users.push(newUser);
});
// When joining a group
socket.on('joinGroup', (groupID: string, userID: string) => {
if (!userID) return;
const user = users.find(user => user.userID === userID);
if (user) {
user.setGroupID(groupID);
}
});
// When being added to a group
socket.on('addedToGroup', (groupID: string) => {
const groupUsers = users.filter(user => user.groupID === groupID);
groupUsers.forEach(user => {
io.to(user.socketID).emit('fetchGroup');
});
});
// When sending a message
socket.on('sendMessage', (groupID: string) => {
const groupUsers = users.filter(user => user.groupID === groupID);
groupUsers.forEach(user => {
io.to(user.socketID).emit('fetchMessage', groupID);
});
});
// When Creating a new group
socket.on('newGroup', () => {
io.emit('fetchGroup');
});
// When disconnecting
socket.on('disconnect', () => {
users = users.filter(user => user.socketID !== socket.id);
});
});
httpServer.listen(port, (err?: any) => {
if (err) throw err;
console.log(
`> Ready on http://localhost:${port} - env ${process.env.NODE_ENV}`
);
});
});