import { Injectable } from '@nestjs/common'; import { VoteCreateDTO } from './vote.dto'; import { Vote } from './vote.entity'; import { Repository } from 'typeorm'; import { InjectRepository } from '@nestjs/typeorm'; interface IAnswer { question_id: string; answer: string; } interface IVote { answers: IAnswer[]; } @Injectable() export class VoteService { constructor( @InjectRepository(Vote) private voteRepository: Repository, ) {} async create(value: VoteCreateDTO) { const vote = Object.entries(value).reduce( (acc, [question_id, a]) => { const answer = String(a); acc.answers.push({ question_id, answer }); return acc; }, { answers: [], }, ); const voteEntity = this.voteRepository.create(vote); await this.voteRepository.save(voteEntity); } async getResults() { const all_votes = await this.voteRepository.find(); const compiled_results: { [question: string]: { [vote: string]: number } } = {}; for (const vote of all_votes) { for (const answer of vote.answers) { if (!(answer.question_id in compiled_results)) { compiled_results[answer.question_id] = {}; } if (!(answer.answer in compiled_results[answer.question_id])) { compiled_results[answer.question_id][answer.answer] = 0; } compiled_results[answer.question_id][answer.answer]++; } } return compiled_results; } }