Skip to content

Commit 3facdf5

Browse files
authored
moved mongo, redis setup to functions (#84)
1 parent 0055134 commit 3facdf5

File tree

3 files changed

+15
-11
lines changed

3 files changed

+15
-11
lines changed

server/src/db/mogoose.ts

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,11 @@ import {
99
export const PollModel = model<PollDocument>('Poll', pollSchema)
1010
export const StudentModel = model<StudentDocument>('Student', studentSchema)
1111

12-
connect(process.env.MONGODB_URL).catch((err) => {
13-
throw err
14-
})
12+
export async function connectMongo () {
13+
await connect(process.env.MONGODB_URL)
14+
db.on('open', () => {
15+
console.log('Connected to mongo')
16+
})
17+
}
1518

1619
export const db = connection

server/src/redis.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,12 @@ import { createClient } from 'redis'
22
import fs from 'fs'
33
import path from 'path'
44
import readline from 'readline'
5+
56
const client = createClient({
67
url: process.env.REDIS_URL
7-
});
8+
})
89

9-
(async () => {
10+
async function connectRedis () {
1011
client.on('error', (err) => console.log('Redis Client Error', err))
1112

1213
await client.connect()
@@ -25,6 +26,6 @@ const client = createClient({
2526
console.log(line.trim())
2627
client.set(line.trim(), 'instructor')
2728
}
28-
})()
29+
}
2930

30-
export { client }
31+
export { client, connectRedis }

server/src/server.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,11 @@ import cors from 'cors'
66
import cookieParser from 'cookie-parser'
77
import { io } from './socket'
88
import pollRouter from './routes/pollRoute'
9-
import { db } from './db/mogoose'
9+
import { connectMongo } from './db/mogoose'
1010
import userRouter from './routes/userRoutes'
1111
import { getUser } from './controllers/userController'
12+
import { connectRedis } from './redis'
1213
dotenv.config()
13-
db.on('open', () => {
14-
console.log('Connected to mongo')
15-
})
1614

1715
// starting the express server
1816
const app = express()
@@ -46,6 +44,8 @@ app.use('/poll', pollRouter)
4644

4745
const server = app.listen(port, () => {
4846
console.log('Listening on http://localhost:' + port)
47+
connectRedis()
48+
connectMongo()
4949
io.attach(server)
5050
io.use(async (socket, next) => {
5151
try {

0 commit comments

Comments
 (0)