forked from quic-issues/427e7578-d7bf-49c8-aee9-2dd999e25316
33 lines
1.1 KiB
TypeScript
33 lines
1.1 KiB
TypeScript
// server/api/polls/[id].ts
|
|
export default defineEventHandler(async (event) => {
|
|
const method = event.node.req.method;
|
|
const pollId = getRouterParam(event, 'id');
|
|
|
|
// We use Nitro's built-in storage.
|
|
// 'polls' is the storage namespace.
|
|
const storage = useStorage('polls');
|
|
|
|
if (!pollId) {
|
|
throw createError({ statusCode: 400, statusMessage: 'Poll ID required' });
|
|
}
|
|
|
|
// GET: Fetch the saved Yjs document state
|
|
if (method === 'GET') {
|
|
const data = await storage.getItem(`poll:${pollId}`);
|
|
// Return the array of numbers (or null if it doesn't exist yet)
|
|
return { update: data || null };
|
|
}
|
|
|
|
// POST: Save a new Yjs document state
|
|
if (method === 'POST') {
|
|
const body = await readBody(event);
|
|
|
|
if (body.update && Array.isArray(body.update)) {
|
|
// Save the binary update (sent as an array of numbers) to storage
|
|
await storage.setItem(`poll:${pollId}`, body.update);
|
|
return { success: true };
|
|
}
|
|
|
|
throw createError({ statusCode: 400, statusMessage: 'Invalid update payload' });
|
|
}
|
|
}); |