|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const db = require.main.require('./src/database'); |
| 4 | +const { v4: uuid } = require('uuid'); |
| 5 | + |
| 6 | +const PollModel = { |
| 7 | + /** |
| 8 | + * Create a poll and index it by postId. |
| 9 | + * @param {Object} p |
| 10 | + * @param {string|number} p.postId |
| 11 | + * @param {string} p.question |
| 12 | + * @param {string[]} p.options - at least 2 |
| 13 | + * @param {string|number} p.createdBy |
| 14 | + * @param {number|null} [p.closesAt] |
| 15 | + */ |
| 16 | + async createPoll({ postId, question, options, createdBy, closesAt = null }) { |
| 17 | + if (!postId || !question || !Array.isArray(options) || options.length < 2) { |
| 18 | + throw new Error('Invalid poll: need postId, question, and at least 2 options'); |
| 19 | + } |
| 20 | + |
| 21 | + const pollId = uuid(); |
| 22 | + |
| 23 | + const pollKey = `poll:${pollId}`; |
| 24 | + const data = { |
| 25 | + pollId, |
| 26 | + postId: String(postId), |
| 27 | + question: String(question), |
| 28 | + options: JSON.stringify(options), |
| 29 | + createdBy: String(createdBy ?? ''), |
| 30 | + createdAt: String(Date.now()), |
| 31 | + closesAt: closesAt ? String(closesAt) : '', |
| 32 | + }; |
| 33 | + |
| 34 | + // Store main poll object |
| 35 | + await db.setObject(pollKey, data); |
| 36 | + |
| 37 | + // Index polls by post (future-proof if you ever allow >1 poll/post) |
| 38 | + await db.setAdd(`poll:byPost:${postId}`, pollId); |
| 39 | + |
| 40 | + // Initialize counts for each option to 0 |
| 41 | + const counts = {}; |
| 42 | + options.forEach((_, idx) => { counts[idx] = 0; }); |
| 43 | + await db.setObject(`poll:counts:${pollId}`, counts); |
| 44 | + |
| 45 | + return { ...data, options }; |
| 46 | + }, |
| 47 | + |
| 48 | + async getPollById(pollId) { |
| 49 | + const obj = await db.getObject(`poll:${pollId}`); |
| 50 | + if (!obj || !obj.pollId) return null; |
| 51 | + return { ...obj, options: JSON.parse(obj.options || '[]') }; |
| 52 | + }, |
| 53 | + |
| 54 | + async getPollIdsByPostId(postId) { |
| 55 | + return db.getSetMembers(`poll:byPost:${postId}`); |
| 56 | + }, |
| 57 | + |
| 58 | + // Common case: one poll per post — return the first if it exists |
| 59 | + async getPollByPostId(postId) { |
| 60 | + const ids = await db.getSetMembers(`poll:byPost:${postId}`); |
| 61 | + if (!ids || !ids.length) return null; |
| 62 | + return this.getPollById(ids[0]); |
| 63 | + }, |
| 64 | +}; |
| 65 | + |
| 66 | +module.exports = PollModel; |
0 commit comments