57 lines
1.3 KiB
JavaScript
57 lines
1.3 KiB
JavaScript
import jwt from "jsonwebtoken";
|
|
import Update from "../../models/update.js";
|
|
import { connectDB } from "../../utils/mongoose.js";
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
await connectDB();
|
|
|
|
const token = getCookie(event, "auth-token");
|
|
|
|
if (!token) {
|
|
throw createError({
|
|
statusCode: 401,
|
|
statusMessage: "Not authenticated",
|
|
});
|
|
}
|
|
|
|
let memberId;
|
|
try {
|
|
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
|
memberId = decoded.memberId;
|
|
} catch (err) {
|
|
throw createError({
|
|
statusCode: 401,
|
|
statusMessage: "Invalid or expired token",
|
|
});
|
|
}
|
|
|
|
const body = await readBody(event);
|
|
|
|
if (!body.content || !body.content.trim()) {
|
|
throw createError({
|
|
statusCode: 400,
|
|
statusMessage: "Content is required",
|
|
});
|
|
}
|
|
|
|
try {
|
|
const update = await Update.create({
|
|
author: memberId,
|
|
content: body.content,
|
|
images: body.images || [],
|
|
privacy: body.privacy || "members",
|
|
commentsEnabled: body.commentsEnabled ?? true,
|
|
});
|
|
|
|
// Populate author details
|
|
await update.populate("author", "name avatar");
|
|
|
|
return update;
|
|
} catch (error) {
|
|
console.error("Create update error:", error);
|
|
throw createError({
|
|
statusCode: 500,
|
|
statusMessage: "Failed to create update",
|
|
});
|
|
}
|
|
});
|