Skip to content

Instantly share code, notes, and snippets.

@PaulieScanlon
Created June 16, 2024 14:40
Show Gist options
  • Save PaulieScanlon/cc95b83bc818468fe0b6b80ed92bb8e8 to your computer and use it in GitHub Desktop.
Save PaulieScanlon/cc95b83bc818468fe0b6b80ed92bb8e8 to your computer and use it in GitHub Desktop.
Result Server Action
// app/results/get-all-votes.ts
'use server';
import { doc } from '../../services/google-spreadsheet';
import config from '../../utils/poll-config';
export default async function getAllVotes() {
try {
await doc.loadInfo();
const sheet = doc.sheetsByIndex[0];
const rows = await sheet.getRows();
const allValues = config.map((value) => {
const { name, id } = value;
return {
name: name,
count: Number(rows[0].get(id)),
};
});
const total = allValues.reduce((values, value) => values + value.count, 0);
const max = Math.max(...allValues.map((item) => item.count));
const results = allValues.map((result, index) => {
const { name, count } = result;
return {
value: name,
count: count,
percent: Number((count * 100) / total).toFixed(1),
max: max,
};
});
return {
total: total,
results: results,
};
} catch (error) {
console.error(error);
return {
total: 0,
results: [],
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment