|
| 1 | +import { Router, Request, Response, NextFunction } from 'express'; |
| 2 | +import { Container } from 'typedi'; |
| 3 | +import { celebrate, Joi } from 'celebrate'; |
| 4 | + |
| 5 | +import CandidateService from '../../services/candidate'; |
| 6 | +import { getLogger } from '../../loaders/dependencyInjector'; |
| 7 | + |
| 8 | +const route = Router(); |
| 9 | + |
| 10 | +export default (app: Router) => { |
| 11 | + app.use('/candidates', route); |
| 12 | + |
| 13 | + route.get('/', async (req: Request, res: Response) => { |
| 14 | + const logger = getLogger(); |
| 15 | + logger.debug('Calling Candidate-List endpoint'); |
| 16 | + const candidateServiceInstance = Container.get(CandidateService); |
| 17 | + const candidates = await candidateServiceInstance.List(); |
| 18 | + return res.json(candidates).status(200); |
| 19 | + }); |
| 20 | + |
| 21 | + route.post( |
| 22 | + '/', |
| 23 | + celebrate({ |
| 24 | + body: Joi.object({ |
| 25 | + name: Joi.string().required(), |
| 26 | + }), |
| 27 | + }), |
| 28 | + async (req: Request, res: Response, next: NextFunction) => { |
| 29 | + const logger = getLogger(); |
| 30 | + logger.debug('Calling Candidate-Create endpoint with body: %o', req.body); |
| 31 | + try { |
| 32 | + const { name } = req.body; |
| 33 | + const candidateServiceInstance = Container.get(CandidateService); |
| 34 | + const { candidate } = await candidateServiceInstance.Create(name); |
| 35 | + return res.json({ candidate }).status(200); |
| 36 | + } catch (e) { |
| 37 | + logger.error('🔥 error: %o', e); |
| 38 | + return next(e); |
| 39 | + } |
| 40 | + }, |
| 41 | + ); |
| 42 | + |
| 43 | + route.put('/:id/vote/', async (req: Request, res: Response, next: NextFunction) => { |
| 44 | + const logger = getLogger(); |
| 45 | + logger.debug('Calling Candidate-Vote endpoint'); |
| 46 | + try { |
| 47 | + const { id } = req.params; |
| 48 | + const candidateServiceInstance = Container.get(CandidateService); |
| 49 | + await candidateServiceInstance.Vote(id); |
| 50 | + return res.json({ message: 'vote success' }).status(200); |
| 51 | + } catch (e) { |
| 52 | + logger.error('🔥 error: %o', e); |
| 53 | + return next(e); |
| 54 | + } |
| 55 | + }); |
| 56 | +}; |
0 commit comments