Skip to content

Commit fdc8825

Browse files
nested routing (#8)
* audit fix * update dependencies * coverted promise to async await * migrated code to nested routing Co-authored-by: Tushar Gupta <cse.tushar@gmail.com>
1 parent afb13bb commit fdc8825

10 files changed

Lines changed: 180 additions & 150 deletions

File tree

Readme.MD

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -18,19 +18,18 @@ If you found this project useful, then please consider giving it a ⭐️ on Git
1818

1919
1. You need to install PostgreSQL
2020

21+
- For Windows
22+
- Install PostgreSQL and set following environment variable
23+
`C:\Program Files\PostgreSQL\10\bin`,
24+
`C:\Program Files\PostgreSQL\10\lib`
25+
- For Ubuntu
2126

22-
- For Windows
23-
- Install PostgreSQL and set following environment variable
24-
`C:\Program Files\PostgreSQL\10\bin`,
25-
`C:\Program Files\PostgreSQL\10\lib`
26-
- For Ubuntu
27+
- Installation
28+
`sudo apt update`
29+
`sudo apt-get install postgresql postgresql-contrib`
2730

28-
- Installation
29-
`sudo apt update`
30-
`sudo apt-get install postgresql postgresql-contrib`
31-
32-
- Manage `PostgreSQL` service
33-
`sudo systemctl {status | start | restart | stop} postgresql`
31+
- Manage `PostgreSQL` service
32+
`sudo systemctl {status | start | restart | stop} postgresql`
3433

3534
2. rename `.env-sample` to `.env` in the file the DB connection string need to be updated according to your `credentials`.
3635
ex : `postgres://<YourUserName>:<YourPassword>@localhost:5432/<YourDatabase>`
@@ -54,14 +53,14 @@ you can change port in `.env` file check `.env-sample`
5453
```
5554
src
5655
└───index.ts # Application entry point
57-
└───routes.ts # Application routes / endpoints
56+
└───routes # Application routes / endpoints
5857
└───controllers # Express route controllers for all the endpoints of the app
58+
└───repositories # All the database interaction logic is here
5959
└───db # DB related files like connection / seed data
6060
└───handlers # Common logic
6161
└───logs # application logs
6262
└───middlewares # express middlewares
6363
└───models # DB Models (Postgress)
64-
└───repositories # All the database interaction logic is here
6564
└───validators # API Request object validations
6665
6766
```

package-lock.json

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

server.ts

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,13 @@ const app: Application = express();
99
const server: Server = new Server(app);
1010
const port: number = parseInt(process.env.port, 10) || 3000;
1111

12-
app.listen(port, 'localhost', function() {
12+
app.listen(port, 'localhost', function () {
1313
console.info(`Server running on : http://localhost:${port}`);
1414
}).on('error', (err: any) => {
15-
if (err.code === 'EADDRINUSE') {
16-
console.log('server startup error: address already in use');
17-
}
18-
else {
19-
console.log(err);
20-
}
15+
if (err.code === 'EADDRINUSE') {
16+
console.log('server startup error: address already in use');
17+
}
18+
else {
19+
console.log(err);
20+
}
2121
});

src/controllers/CoursesCtrl.ts

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,29 @@
1-
import { Router, Request, Response, NextFunction } from 'express';
1+
import { Request, Response, NextFunction } from 'express';
22
import CourseRepo from './../repositories/CoursesRepo';
33
import { apiErrorHandler } from './../handlers/errorHandler';
44

5-
export default class CoursesRoutes {
6-
constructor() {}
5+
export default class CoursesCtrl {
6+
constructor() { }
77

8-
getAllCourses(req: Request, res: Response, next: NextFunction) {
9-
CourseRepo.getAllCourses({ order: ['seqNo'] })
10-
.then(result => res.json(result))
11-
.catch(err => {
12-
apiErrorHandler(err, req, res, 'Fetch All Courses failed.');
13-
});
8+
async getAllCourses(req: Request, res: Response, next: NextFunction) {
9+
try {
10+
const courseList = await CourseRepo.getAllCourses({ order: ['seqNo'] })
11+
res.json(courseList);
12+
} catch (error) {
13+
apiErrorHandler(error, req, res, 'Fetch All Courses failed.');
14+
}
1415
}
1516

16-
getCourseDetails(req: Request, res: Response, next: NextFunction) {
17-
CourseRepo.getById(req.params.id)
18-
.then(result => {
19-
if (result) {
20-
return res.json(result);
21-
} else {
22-
res.status(404).send(`Lesson ${req.params.id} not found.`);
23-
}
24-
})
25-
.catch(err => {
26-
apiErrorHandler(err, req, res, `Course ${req.params.id} is failed.`);
27-
});
17+
async getCourseDetails(req: Request, res: Response, next: NextFunction) {
18+
try {
19+
const courseDetails = await CourseRepo.getById(req.params.id);
20+
if (courseDetails) {
21+
return res.json(courseDetails);
22+
} else {
23+
res.status(404).send(`Lesson ${req.params.id} not found.`);
24+
}
25+
} catch (error) {
26+
apiErrorHandler(error, req, res, `Course ${req.params.id} is failed.`);
27+
}
2828
}
2929
}

src/controllers/LessonsCtrl.ts

Lines changed: 64 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -1,78 +1,82 @@
1-
import { NextFunction, Request, Response, Router } from 'express';
1+
import { Request, Response, NextFunction } from 'express';
22
import { apiErrorHandler } from '../handlers/errorHandler';
33
import LessonRepo from '../repositories/LessonsRepo';
44

5-
export default class LessonRoutes {
6-
constructor() {}
5+
export default class LessonsCtrl {
6+
constructor() { }
77

8-
getAllLessons(req: Request, res: Response, next: NextFunction) {
9-
LessonRepo.getAllLessons({ order: ['id'] })
10-
.then(result => res.json(result))
11-
.catch(err => {
12-
apiErrorHandler(err, req, res, 'Fetch All Lessons failed.');
13-
});
8+
async getAllLessons(req: Request, res: Response, next: NextFunction) {
9+
try {
10+
const lessons = await LessonRepo.getAllLessons({ order: ['id'] });
11+
res.json(lessons);
12+
} catch (error) {
13+
apiErrorHandler(error, req, res, 'Fetch All Lessons failed.');
14+
}
1415
}
1516

16-
getLessonByCourse(req: Request, res: Response, next: NextFunction) {
17-
LessonRepo.getLessonByCourse(req.params.id)
18-
.then(result => res.json(result))
19-
.catch(err => {
20-
apiErrorHandler(
21-
err,
22-
req,
23-
res,
24-
`Lessons in course ${req.params.id} failed.`,
25-
);
26-
});
17+
async getLessonByCourse(req: Request, res: Response, next: NextFunction) {
18+
try {
19+
const lesson = await LessonRepo.getLessonByCourse(req.params.id);
20+
res.json(lesson);
21+
} catch (error) {
22+
apiErrorHandler(
23+
error,
24+
req,
25+
res,
26+
`Lessons in course ${req.params.id} failed.`,
27+
);
28+
}
2729
}
2830

29-
getLessonById(req: Request, res: any, next: NextFunction) {
30-
LessonRepo.getLessonById(req.params.id)
31-
.then(result => {
32-
if (result) {
33-
return res.json(result);
34-
} else {
35-
res.status(404).send(`Lesson ${req.params.id} not found.`);
36-
}
37-
})
38-
.catch(err => {
39-
apiErrorHandler(err, req, res, `Lesson ${req.params.id} failed.`);
40-
});
31+
async getLessonById(req: Request, res: any, next: NextFunction) {
32+
try {
33+
const result = await LessonRepo.getLessonById(req.params.id);
34+
if (result) {
35+
return res.json(result);
36+
} else {
37+
res.status(404).send(`Lesson ${req.params.id} not found.`);
38+
}
39+
} catch (error) {
40+
apiErrorHandler(error, req, res, `Lesson ${req.params.id} failed.`);
41+
}
4142
}
4243

43-
createLesson(req: Request, res: Response, next: NextFunction) {
44-
LessonRepo.createLesson(req['value']['body'])
45-
.then(result => res.json(result))
46-
.catch(err => {
47-
apiErrorHandler(err, req, res, 'Creation of Lesson failed.');
48-
});
44+
async createLesson(req: Request, res: Response, next: NextFunction) {
45+
try {
46+
const result = await LessonRepo.createLesson(req['value']['body']);
47+
res.json(result);
48+
} catch (error) {
49+
apiErrorHandler(error, req, res, 'Creation of Lesson failed.');
50+
}
4951
}
5052

51-
updateLesson(req: Request, res: Response, next: NextFunction) {
53+
async updateLesson(req: Request, res: Response, next: NextFunction) {
5254
const id = parseInt(req.params.id);
53-
LessonRepo.updateLesson(id, req['value']['body'])
54-
.then(result => res.json(result))
55-
.catch(err => {
56-
apiErrorHandler(
57-
err,
58-
req,
59-
res,
60-
`updation of Lesson ${req.params.id} is failed.`,
61-
);
62-
});
55+
try {
56+
const result = await LessonRepo.updateLesson(id, req['value']['body']);
57+
res.json(result);
58+
} catch (error) {
59+
apiErrorHandler(
60+
error,
61+
req,
62+
res,
63+
`updation of Lesson ${req.params.id} is failed.`,
64+
);
65+
}
6366
}
6467

65-
deleteLesson(req: Request, res: Response, next: NextFunction) {
68+
async deleteLesson(req: Request, res: Response, next: NextFunction) {
6669
const id = parseInt(req.params.id);
67-
LessonRepo.deleteLesson(id)
68-
.then(result => res.json(result))
69-
.catch(err => {
70-
apiErrorHandler(
71-
err,
72-
req,
73-
res,
74-
`deletion of Lesson ${req.params.id} is failed.`,
75-
);
76-
});
70+
try {
71+
const result = await LessonRepo.deleteLesson(id);
72+
res.json(result);
73+
} catch (error) {
74+
apiErrorHandler(
75+
error,
76+
req,
77+
res,
78+
`deletion of Lesson ${req.params.id} is failed.`,
79+
);
80+
}
7781
}
7882
}

src/routes.ts

Lines changed: 0 additions & 37 deletions
This file was deleted.

src/routes/CourseRoutes.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { Router } from 'express';
2+
import CoursesCtrl from '../controllers/CoursesCtrl';
3+
4+
class CourseRoutes {
5+
router = Router();
6+
coursesCtrl = new CoursesCtrl();
7+
8+
constructor() {
9+
this.intializeRoutes();
10+
}
11+
intializeRoutes() {
12+
this.router.route('/').get(this.coursesCtrl.getAllCourses);
13+
this.router.route('/:id').get(this.coursesCtrl.getCourseDetails);
14+
}
15+
}
16+
export default new CourseRoutes().router;

src/routes/LessonRoutes.ts

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import { Router } from 'express';
2+
import LessonsCtrl from '../controllers/LessonsCtrl';
3+
import { LessonValidator, lessonSchema } from '../validators/lessonValidator';
4+
5+
class LessonRoutes {
6+
router = Router();
7+
lessonsCtrl = new LessonsCtrl();
8+
lessonValidator = new LessonValidator();
9+
10+
constructor() {
11+
this.intializeRoutes();
12+
}
13+
14+
intializeRoutes() {
15+
16+
this.router.route('/').get(this.lessonsCtrl.getAllLessons);
17+
this.router.route('/course/:id')
18+
.get(this.lessonsCtrl.getLessonByCourse);
19+
this.router.route('/:id').get(this.lessonsCtrl.getLessonById);
20+
this.router.route('/')
21+
.post(
22+
this.lessonValidator.validateBody(lessonSchema),
23+
this.lessonsCtrl.createLesson
24+
);
25+
this.router.route('/:id')
26+
.put(
27+
this.lessonValidator.validateBody(lessonSchema),
28+
this.lessonsCtrl.updateLesson
29+
);
30+
this.router.route('/:id').delete(this.lessonsCtrl.deleteLesson);
31+
}
32+
}
33+
34+
export default new LessonRoutes().router;

src/routes/index.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import { Application } from 'express';
2+
import courseRouter from './CourseRoutes';
3+
import lessonRouter from './LessonRoutes'
4+
5+
export default class Routes {
6+
7+
constructor(app: Application) {
8+
// course reoutes
9+
app.use('/api/courses', courseRouter);
10+
// lesson routes
11+
app.use('/api/lessons', lessonRouter);
12+
}
13+
}

0 commit comments

Comments
 (0)