|
| 1 | +import { createHash } from 'node:crypto' |
| 2 | + |
| 3 | +import { Injectable, Logger } from '@nestjs/common' |
| 4 | + |
| 5 | +import { InjectModel } from '~/transformers/model.transformer' |
| 6 | + |
| 7 | +import { PollVoteModel } from './poll-vote.model' |
| 8 | + |
| 9 | +export interface PollState { |
| 10 | + tallies: Record<string, number> |
| 11 | + totalVotes: number |
| 12 | + userVote?: string[] |
| 13 | + status: 'ready' | 'error' |
| 14 | + closed: boolean |
| 15 | + canVote: boolean |
| 16 | + errorMessage?: string |
| 17 | +} |
| 18 | + |
| 19 | +interface FingerprintInput { |
| 20 | + readerId?: string | null |
| 21 | + ip: string |
| 22 | + agent: string |
| 23 | +} |
| 24 | + |
| 25 | +@Injectable() |
| 26 | +export class PollService { |
| 27 | + private readonly logger = new Logger(PollService.name) |
| 28 | + |
| 29 | + constructor( |
| 30 | + @InjectModel(PollVoteModel) |
| 31 | + private readonly model: MongooseModel<PollVoteModel>, |
| 32 | + ) {} |
| 33 | + |
| 34 | + /** |
| 35 | + * Stable identity for vote dedup. Logged-in readers map to `r:<id>`; |
| 36 | + * anonymous voters hash IP + UA into `a:<hex>`. |
| 37 | + */ |
| 38 | + computeFingerprint({ readerId, ip, agent }: FingerprintInput): string { |
| 39 | + if (readerId) return `r:${readerId}` |
| 40 | + const digest = createHash('sha256') |
| 41 | + .update(`${ip}|${agent}`) |
| 42 | + .digest('hex') |
| 43 | + .slice(0, 32) |
| 44 | + return `a:${digest}` |
| 45 | + } |
| 46 | + |
| 47 | + async getState(pollId: string, voterFingerprint: string): Promise<PollState> { |
| 48 | + const [tallyDocs, vote, totalVotes] = await Promise.all([ |
| 49 | + this.model |
| 50 | + .aggregate<{ |
| 51 | + _id: string |
| 52 | + count: number |
| 53 | + }>([{ $match: { pollId } }, { $unwind: '$optionIds' }, { $group: { _id: '$optionIds', count: { $sum: 1 } } }]) |
| 54 | + .exec(), |
| 55 | + this.model.findOne({ pollId, voterFingerprint }).lean().exec(), |
| 56 | + this.model.countDocuments({ pollId }).exec(), |
| 57 | + ]) |
| 58 | + |
| 59 | + const tallies: Record<string, number> = {} |
| 60 | + for (const doc of tallyDocs) tallies[doc._id] = doc.count |
| 61 | + |
| 62 | + return { |
| 63 | + tallies, |
| 64 | + totalVotes, |
| 65 | + userVote: vote?.optionIds, |
| 66 | + status: 'ready', |
| 67 | + closed: false, |
| 68 | + canVote: !vote, |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + async batchGetStates( |
| 73 | + pollIds: string[], |
| 74 | + voterFingerprint: string, |
| 75 | + ): Promise<Record<string, PollState>> { |
| 76 | + const out: Record<string, PollState> = {} |
| 77 | + await Promise.all( |
| 78 | + pollIds.map(async (pollId) => { |
| 79 | + out[pollId] = await this.getState(pollId, voterFingerprint) |
| 80 | + }), |
| 81 | + ) |
| 82 | + return out |
| 83 | + } |
| 84 | + |
| 85 | + async submit( |
| 86 | + pollId: string, |
| 87 | + voterFingerprint: string, |
| 88 | + optionIds: string[], |
| 89 | + ): Promise<PollState> { |
| 90 | + try { |
| 91 | + await this.model.create({ pollId, voterFingerprint, optionIds }) |
| 92 | + } catch (err: any) { |
| 93 | + if (err?.code === 11_000) { |
| 94 | + const state = await this.getState(pollId, voterFingerprint) |
| 95 | + return { ...state, status: 'error', errorMessage: 'Already voted' } |
| 96 | + } |
| 97 | + throw err |
| 98 | + } |
| 99 | + return this.getState(pollId, voterFingerprint) |
| 100 | + } |
| 101 | +} |
0 commit comments