Skip to content

Commit d426e7a

Browse files
committed
refactoring for ts and es6 modules
1 parent c848313 commit d426e7a

File tree

5 files changed

+124
-97
lines changed

5 files changed

+124
-97
lines changed

server/db/mongo.ts

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,35 @@
1-
const { MongoClient } = require("mongodb");
1+
import {MongoClient} from 'mongodb';
22

3-
const uri = "mongodb://localhost:27017/?readPreference=primary&ssl=false";
3+
const uri = 'mongodb://localhost:27017/?readPreference=primary&ssl=false';
44

55
const client = new MongoClient(uri);
66

77
let dbConnection: any;
88

9-
export function connectToServer (callback: any) {
10-
client.connect(function (err: undefined, db: { db: (arg0: string) => any; }) {
9+
/**
10+
* @param {Function} callback callback function
11+
* @returns {any} Callback
12+
*/
13+
function connectToServer(callback: Function): any {
14+
client.connect((err, db) => {
1115
if (err || !db) {
1216
return callback(err);
1317
}
1418

15-
dbConnection = db.db("zHomeMedia");
16-
console.log("Successfully connected to MongoDB.");
19+
dbConnection = db.db('zHomeMedia');
20+
console.log('Successfully connected to MongoDB.');
1721

1822
return callback();
1923
});
24+
25+
return null;
2026
}
2127

22-
export function getDb () {
28+
/**
29+
* @returns {any} Database connection object
30+
*/
31+
function getDb(): any {
2332
return dbConnection;
2433
}
34+
35+
export {connectToServer, getDb};

server/endpoints/auth.ts

Lines changed: 28 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,22 @@
1+
import 'dotenv/config';
12
import express from 'express';
2-
import { getDb } from '../db/mongo';
3-
import dotenv from 'dotenv';
43
import bcrypt from 'bcrypt';
4+
import {getDb} from '../db/mongo.js';
55

6-
dotenv.config();
7-
6+
/* eslint new-cap: ["error", { "capIsNewExceptions": ["Router"] }] */
87
const auth = express.Router();
98
// const saltRounds = Number(process.env.SALT_ROUNDS);
109

1110
declare module 'express-session' {
11+
// eslint-disable-next-line no-unused-vars
1212
interface SessionData {
1313
userId: string;
1414
user: string;
1515
}
1616
}
1717

18-
auth.post('/', function (req, res) {
19-
const { user, password, remember } = req.body;
18+
auth.post('/', function(req, res) {
19+
const {user, password} = req.body;
2020

2121
if (
2222
user !== undefined &&
@@ -27,43 +27,43 @@ auth.post('/', function (req, res) {
2727
const db = getDb();
2828

2929
db.collection('users')
30-
.findOne({ username: user })
31-
.then((dbResult: any) => {
32-
if (dbResult !== null) {
33-
bcrypt.compare(
34-
password,
35-
dbResult.password,
36-
function (_err, authResult) {
37-
if (authResult) {
38-
req.session.userId = dbResult._id;
39-
req.session.user = dbResult.username;
40-
res.json({ user: dbResult.username });
41-
return;
42-
}
30+
.findOne({username: user})
31+
.then((dbResult: any) => {
32+
if (dbResult !== null) {
33+
bcrypt.compare(
34+
password,
35+
dbResult.password,
36+
function(_err, authResult) {
37+
if (authResult) {
38+
req.session.userId = dbResult._id;
39+
req.session.user = dbResult.username;
40+
res.json({user: dbResult.username});
41+
return;
42+
}
4343

44-
res.status(400).send('Invalid credentials');
45-
}
46-
);
44+
res.status(400).send('Invalid credentials');
45+
},
46+
);
4747

48-
return;
49-
}
48+
return;
49+
}
5050

51-
res.status(400).send('Invalid credentials');
52-
});
51+
res.status(400).send('Invalid credentials');
52+
});
5353

5454
return;
5555
}
5656

5757
res.status(400).send('Invalid credentials');
5858
});
5959

60-
auth.get('/logout', function (req, res) {
60+
auth.get('/logout', function(req, res) {
6161
req.session.destroy(() => {
6262
res.sendStatus(200);
6363
});
6464
});
6565

66-
auth.get('/info', function (req, res) {
66+
auth.get('/info', function(req, res) {
6767
if (req.session.userId === undefined) {
6868
res.status(400).send('Invalid credentials');
6969
return;

server/endpoints/image.ts

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,16 @@
11
import express from 'express';
22
import fs from 'fs';
33

4+
/* eslint new-cap: ["error", { "capIsNewExceptions": ["Router"] }] */
45
const image = express.Router();
56

6-
image.get('/image/:imageId', function (req, res) {
7+
image.get('/image/:imageId', function(req, res) {
78
const imageId = parseInt(req.params.imageId);
8-
let filename = imageId + '.jpg';
9+
const filename = imageId + '.jpg';
910

10-
var img = fs.readFileSync('store/images/files/' + filename);
11-
res.writeHead(200, { 'Content-Type': 'image/jpg' });
11+
const img = fs.readFileSync('store/images/files/' + filename);
12+
res.writeHead(200, {'Content-Type': 'image/jpg'});
1213
res.end(img, 'binary');
1314
});
1415

15-
export default image;
16+
export default image;

server/middleware/requireAuth.ts

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
1-
import { Request, Response, NextFunction } from 'express';
1+
import {Request, Response, NextFunction} from 'express';
22

3-
function requireAuth (req: Request, res: Response, next: NextFunction) {
3+
/**
4+
*
5+
* @param {Request} req Request object
6+
* @param {Response} res Response object
7+
* @param {NextFunction} next NextFunction
8+
*/
9+
function requireAuth(req: Request, res: Response, next: NextFunction) {
410
// console.log(req.path);
511
// console.log(req.session);
612

@@ -12,7 +18,7 @@ function requireAuth (req: Request, res: Response, next: NextFunction) {
1218
}
1319
}
1420

15-
next()
21+
next();
1622
}
1723

18-
export default requireAuth;
24+
export default requireAuth;

server/server.ts

Lines changed: 62 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -1,66 +1,75 @@
1+
import 'dotenv/config';
12
import express from 'express';
2-
import dotenv from 'dotenv';
33
import cors from 'cors';
4-
import { connectToServer } from './db/mongo';
54
import cookieParser from 'cookie-parser';
6-
import auth from './endpoints/auth';
7-
import video from './endpoints/video';
8-
import videos from './endpoints/videos';
9-
import image from './endpoints/image';
10-
import requireAuth from './middleware/requireAuth';
115
import connectRedis from 'connect-redis';
12-
import { createClient } from 'redis';
6+
import {createClient} from 'redis';
137
import session from 'express-session';
8+
import fileupload from 'express-fileupload';
9+
import fs from 'fs';
10+
import {connectToServer} from './db/mongo.js';
11+
import auth from './endpoints/auth.js';
12+
import video from './endpoints/video.js';
13+
import videos from './endpoints/videos.js';
14+
import image from './endpoints/image.js';
15+
import requireAuth from './middleware/requireAuth.js';
1416

15-
const RedisStore = connectRedis(session);
16-
const redisClient = createClient({ legacyMode: true });
17-
redisClient
18-
.connect()
19-
.then(() => {
20-
console.log('redis connected');
21-
})
22-
.catch(console.error);
17+
if (!fs.existsSync(process.env.STORAGE as string)) {
18+
console.log('Storage not found, server not running.');
19+
process.exitCode = 1;
20+
} else {
21+
const RedisStore = connectRedis(session);
22+
const redisClient = createClient({legacyMode: true});
23+
redisClient
24+
.connect()
25+
.then(() => {
26+
console.log('redis connected');
27+
})
28+
.catch(console.error);
2329

24-
dotenv.config();
30+
const app = express();
31+
const port = process.env.PORT;
32+
const allowedOrigins = ['http://localhost', 'http://localhost:8080'];
2533

26-
const app = express();
27-
const port = process.env.PORT;
28-
const allowedOrigins = ['http://localhost', 'http://localhost:8080'];
34+
const options: cors.CorsOptions = {
35+
origin: allowedOrigins,
36+
credentials: true,
37+
};
2938

30-
const options: cors.CorsOptions = {
31-
origin: allowedOrigins,
32-
credentials: true,
33-
};
39+
app.use(
40+
session({
41+
store: new RedisStore({client: redisClient}),
42+
secret: process.env.SESSION_SECRET as string,
43+
resave: false,
44+
saveUninitialized: false,
45+
cookie: {
46+
secure: false, // Change in production
47+
httpOnly: true,
48+
},
49+
}),
50+
);
51+
app.use(cors(options));
52+
app.use(cookieParser());
53+
app.use(requireAuth);
54+
app.use(express.json());
55+
app.use(fileupload({
56+
useTempFiles: true,
57+
tempFileDir: '/tmp/',
58+
}));
3459

35-
app.use(
36-
session({
37-
store: new RedisStore({ client: redisClient }),
38-
secret: process.env.SESSION_SECRET as string,
39-
resave: false,
40-
saveUninitialized: false,
41-
cookie: {
42-
secure: false, // Change in production
43-
httpOnly: true,
44-
},
45-
})
46-
);
47-
app.use(cors(options));
48-
app.use(cookieParser());
49-
app.use(requireAuth);
50-
app.use(express.json());
60+
app.use('/api/auth', auth);
61+
app.use('/api/video', video);
62+
app.use('/api/videos', videos);
63+
app.use('/api/image', image);
5164

52-
app.use('/api/auth', auth);
53-
app.use('/api/video', video);
54-
app.use('/api/videos', videos);
55-
app.use('/api/image', image);
65+
connectToServer(function(error: any) {
66+
if (error) {
67+
console.log(error);
68+
process.exit();
69+
}
5670

57-
connectToServer(function (error: any) {
58-
if (error) {
59-
console.log(error);
60-
process.exit();
61-
}
62-
63-
app.listen(port, function () {
64-
console.log(`[server]: Server is running on port ${port}`);
71+
app.listen(port, function() {
72+
console.log(`[server]: Server is running on port ${port}`);
73+
});
6574
});
66-
});
75+
}

0 commit comments

Comments
 (0)