-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathHeroRouter.ts
60 lines (52 loc) · 1.21 KB
/
HeroRouter.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
import {Router, Request, Response, NextFunction} from 'express';
const Heroes = require('../data');
export class HeroRouter {
router: Router
/**
* Initialize the HeroRouter
*/
constructor() {
this.router = Router();
this.init();
}
/**
* GET all Heroes.
*/
public getAll(req: Request, res: Response, next: NextFunction) {
res.send(Heroes);
}
/**
* GET one hero by id
*/
public getOne(req: Request, res: Response, next: NextFunction) {
let query = parseInt(req.params.id);
let hero = Heroes.find(hero => hero.id === query);
if (hero) {
res.status(200)
.send({
message: 'Success',
status: res.status,
hero
});
}
else {
res.status(404)
.send({
message: 'No hero found with the given id.',
status: res.status
});
}
}
/**
* Take each handler, and attach to one of the Express.Router's
* endpoints.
*/
init() {
this.router.get('/', this.getAll);
this.router.get('/:id', this.getOne);
}
}
// Create the HeroRouter, and export its configured Express.Router
const heroRoutes = new HeroRouter();
heroRoutes.init();
export default heroRoutes.router;