first version
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
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<Vote>,
|
||||
) {}
|
||||
async create(value: VoteCreateDTO) {
|
||||
const vote = Object.entries(value).reduce<IVote>(
|
||||
(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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user